6 CLEAN Tips To IMPROVE Your Python Functions

Sdílet
Vložit
  • čas přidán 19. 06. 2024
  • Here are 6 clean tips that you can use for improving the readability & the practicality of your functions in Python.
    ▶ Become job-ready with Python:
    www.indently.io
    ▶ Follow me on Instagram:
    / indentlyreels

Komentáře • 76

  • @dragweb7725
    @dragweb7725 Před 3 měsíci +14

    Another tip i would recommend, is do not be afraid to have function names a bit longer if it is more self-explanatory
    (for example, a function sorting a list a certain specific way should not be called something like "sort_list()" or "custom_sort()", give a hint of how it sorts the list exactly, like "sort_by_descending_order()")

    • @josephgaviota
      @josephgaviota Před 3 měsíci +4

      Agree. I always say "don't sacrifice clarity for keystrokes."

    • @saaofficial5415
      @saaofficial5415 Před 2 měsíci +1

      How about "sort_descending()" 😊

    • @cerealport2726
      @cerealport2726 Před měsícem +2

      yes, i like this. When i started coding, I didnt; but I do now, for my own sanity, but also for anyone else using the code.

  • @jakedeschamps4454
    @jakedeschamps4454 Před rokem +41

    Wow, I didn't even know I could specify return type and parameter type in python! I used to think that my python code looked super messy and potentially unpredictable compared to other languages. I'll definitely be making use of this!

    • @volbla
      @volbla Před rokem +3

      It is a fairly recent addition, i think. Or at least recently integrated into the language standard.

    • @jakedeschamps4454
      @jakedeschamps4454 Před rokem

      @@volbla that makes sense. I haven't used python in quite a while. My attention has mostly been on C, and also a little C# and C++.

    • @BeenThrDunThat
      @BeenThrDunThat Před rokem +11

      Just keep in mind it is just a hint for the IDE, no type checking at runtime. Still useful for development though especially with multiple devs sharing code

  • @fernandomassey3140
    @fernandomassey3140 Před 3 měsíci +2

    Great job on the video, it was well put together and Thorough. I like how you use functions that have real world application instead of useless functionality. Also how it has real functionality how multiple functions interact with each other. Great job!

  • @MechMK1
    @MechMK1 Před rokem +41

    I love how in the pre-type-hint-era, many Python devs were very smug about how amazing it is to not have to specify your types. Type Hints get added, and now they're all figuring out that being somewhat strict about what types you pass around actually makes sense.
    It's almost as if being strict while writing makes things much easier when reading.

    • @catdisc5304
      @catdisc5304 Před rokem +10

      At the same time, type hints in python don't do shit. They're just there for your code editor to help you debug faster. They get ignored by the interpreter, just like comments.
      You can define a function to return int and have it return a string and the code will run without errors. Your editor will just be angry and tell you "expected type int, returned type Str"

    • @VojtechMach
      @VojtechMach Před rokem +6

      Without typehints, Python would not be a feasible option for large projects IMO.

    • @kellymoses8566
      @kellymoses8566 Před 3 měsíci

      @@catdisc5304 No, you configure PyCharm to treat the wrong type being passed as an error.

    • @HansStrijker
      @HansStrijker Před 2 měsíci

      @@VojtechMach I don't know Voj, a large chuck of the IT world seems to disagree. Python had been used for exceptionally large projects before type hints were added. It's perfectly usable without, but they are often very convenient.
      Personally I certainly do not use typehints all the time, especially not in the first stages of code writing. I find them to be quite annoying while I haven't figured out the global structure of the project. However I do use them quite a lot. Though I already did so before PEP484 just by adding something like _:type arg1: int_ in the docstring.
      Also, as catdisc mentioned, type hints aren't enforced during code execution, so you still generally make duck typing structures to catch errors. It's all a tradeoff. I use C/C++ or Go in situations where strict and strong typing are required. I use Python when it isn't, or when development time (or ease) is preferable.

  • @davidl3383
    @davidl3383 Před rokem +6

    thank you so much. Your chanel helps me a lot to improve my learning of python. Good practices, tips etc. So this morning, I changed my code to add these good practices ;) Very nice these little videos on specifics points. Congrats

  • @ashersaipe
    @ashersaipe Před rokem +2

    I've been binging your videos lol they're so great. If you haven't already, I'd love to see you make a video about generators and the "yield" keyword. I really don't understand it but I'm sure you could explain it well :)

  • @SP-db6sh
    @SP-db6sh Před rokem +5

    Use match statements with walrus... Deadly combo for beautification of this code

  • @fredflintstone8048
    @fredflintstone8048 Před 8 měsíci

    Excellent advice. Thank you for sharing.

  • @legr4ndk891
    @legr4ndk891 Před 2 měsíci +1

    If only the world could write code as beautifully as this.😇

  • @ShivaniSingh-ce6vb
    @ShivaniSingh-ce6vb Před rokem

    Man, you are awesome I loved this video I would like to watch more of these.

  • @WhyNotProgram
    @WhyNotProgram Před rokem +1

    Good stuff! I still make that #4 mistake quite often in my python apps and pay for it later with code refactors haha

  • @whkoh7619
    @whkoh7619 Před rokem

    Great intermediate level tips! Thanks

  • @master_sergik
    @master_sergik Před rokem

    Very useful tips, thanks 👍

  • @yeahnick4260
    @yeahnick4260 Před 3 měsíci

    6:02 SICK ! that is what i was looking for long time ! n1 thank you !

  • @judithlee7989
    @judithlee7989 Před rokem

    Can you do a tutorial on how to properly write function/module documentations? Thanks!!!

  • @hlubradio2318
    @hlubradio2318 Před 2 měsíci

    Very nice I didn't know that's what a doc string is for

  • @muntadher8087
    @muntadher8087 Před rokem

    Useful information thanks

  • @arthurarashbricenoheidari2858
    @arthurarashbricenoheidari2858 Před 10 měsíci

    i loved your videos thanks a lot man

  • @fullstackspiderman
    @fullstackspiderman Před 3 měsíci

    @3:40: you added type hints as float for *numbers parameter and the return type but the result was in int. Could you please explain?

  • @castlecodersltd
    @castlecodersltd Před rokem

    Some great tips, thanks ☺. Is there a pythonic reason for all lower case function names with an under in between words? I personally don't like the underscore in function names and prefer PascalCase (uppercased first letter of each word in the function name) for names, they stand out more.

    • @Indently
      @Indently  Před rokem +3

      I wouldn’t be able to give you any history lessons on that. But that’s the proper naming convention for Python!

    • @larseneivind
      @larseneivind Před rokem +3

      Yes, it is to see the difference between a fuction and a class.

    • @volbla
      @volbla Před rokem +1

      Like Eivind said, it's the python convention to use snake_case for functions and variables, and PascalCase for classes. I'm sure you can find the rationale behind that in pep8, which is like the official python style guide.

  • @littledonkey4925
    @littledonkey4925 Před rokem

    Hi, nice CZcams channel. I have one question:
    3:24 - why didn't the interpreter yell about returning integers, when you have "-> float" next to the function?

    • @volbla
      @volbla Před rokem +2

      That's actually an implicit exception. It is so common to want to accept both ints and floats, so it was decided that any "float" type hint will also accept ints.
      It is very easy to write union types these days, e.g. `int | float`, but this shorthand is still a thing.

  • @RobinZuFALL
    @RobinZuFALL Před rokem

    Where can i get that white python hoodie?

  • @felicytatomaszewska2934
    @felicytatomaszewska2934 Před 2 měsíci

    After watching these videos, I have started valuing VS Code more.

  • @fluffykitties9020
    @fluffykitties9020 Před rokem +1

    hi. for function return notation (point 1) why not just look at the return statement or add a comment to have notation of return type? are there any other advantages to this style of notation that make up for (visually) turning code into garbally gouk?

    • @volbla
      @volbla Před rokem +3

      It lets your code editor know your intentions so it can automatically verify that all return statements and function calls are of the specified type. That's easier than manually checking comments every time you update or call a function.

    • @dragweb7725
      @dragweb7725 Před 3 měsíci

      For your first proposition, in a function returning a variable for example, it can be unclear what type the variable is just by looking at it, and then you're forced to follow the entire function algorithm to get it.
      About the comment, it is better than nothing, but the Type Hints get reported in docstring description that shows to you when passing over the function call, comments do not, so as a user of someone else's function you would be forced to go read explicitly the function again to see the comments.

  • @kelvenlim9283
    @kelvenlim9283 Před rokem +1

    For tip 4, is it something like making the functions as atomic as possible? (I borrow the term "atomic" from databases which means the smallest components)

    • @anthonydesouza9983
      @anthonydesouza9983 Před rokem +3

      Atomic actually refers to indivisible blocks (remember, you can’t break an atom into smaller components). An atomic block can actually be quite large as long as it’s run atomically. In terms of a database, you can use something called “transactions” for things that need to be run all together. For example, if you need to create a row for each step in a recipe, you could do that in a transactions. If for some reason the last step fails a DB constraint and can’t be inserted, the entire transaction is rolled back. So it’s “all or nothing”, and you can’t split up the transaction into smaller sub transactions.
      Tip 4 is actually closer to a concept called SRP, single responsibility principle. Each function should have exactly one responsibility. If you have a function with two responsibilities, you can split it into two smaller and simpler functions.
      SRP is part of a set of rules called SOLID, which I recommend checking out since following the rules leads to clear, maintainable code

    • @Indently
      @Indently  Před rokem +1

      A truly informative comment, thanks Anthony!

    • @samueljehanno
      @samueljehanno Před rokem

      ​@@anthonydesouza9983 👍

  • @jonathanlloyd8688
    @jonathanlloyd8688 Před rokem

    Hi, I am using vs code and when I type hint my return type some of my keywords turn white. I am using vs code. Can anyone help me out here?

  • @haarissultan8866
    @haarissultan8866 Před 3 měsíci

    In your last tip are you saying we should not use globals at all?

  • @behnamheydarian9569
    @behnamheydarian9569 Před 9 měsíci

    I just watched this video, and after tip num 6, i have questions.
    If we import modules outside of the function and using it in our function, then when we use the function in another file, do we get an error because we didn't import a module, or it will import automatically?

    • @dragweb7725
      @dragweb7725 Před 3 měsíci

      Yes, if the function is in another file, you have to import the module in the file where the function is. However, if you do not use the module directly in your main file, you can just import your function from the other file and use it without re-importing the module

  • @yapnog603
    @yapnog603 Před rokem +2

    How do you do that arrow head after the def func?

    • @KevinArellano
      @KevinArellano Před rokem

      It's on pycharm.

    • @constantinschultz7253
      @constantinschultz7253 Před rokem +2

      It is just a dash "-" and a larger than ">"

    • @brainsmoothheadempty
      @brainsmoothheadempty Před rokem +7

      It's a ligature. It automatically replaces sets of characters if you have ligatures enabled in your editor settings. In this case, it's the ligatures of the default JetBrains Mono font in PyCharm.

    • @L0V3V4MP1R3
      @L0V3V4MP1R3 Před rokem +1

      Font ligatures

  • @JordanMetroidManiac
    @JordanMetroidManiac Před rokem

    I think avoiding the global keyword is the best tip because it usually means you need to define an object which handles internal or persistent data automatically. I really cannot think of an instance where you must use the global keyword.

    • @Indently
      @Indently  Před rokem

      I’ve never used it off the top of my head, except when I was new to programming. But I’d love to hear input from other professionals in the field regarding it?

    • @VojtechMach
      @VojtechMach Před rokem

      Probably some kind of read-once settings or config for your app could be a global variable. But I guess there is a better way to store settings. (also better than env. variables)

  • @PanduPoluan
    @PanduPoluan Před rokem +1

    I see you using PyCharm. Man of class 👍🏼

  • @kcvinu
    @kcvinu Před rokem +1

    Few days ago, I needed to use a numpy function. One of the two parameters of that function is shape. I have no idea about the type of that parameter. So I refered to numpy docs. Sadly, there was no clue about that. But I got a link to source of code of that function. I felt very happy, because, I thought I can now read and understand what the shape is. But sadly, it was a parameter with default value None. And the docstring says nothing about the type or nature of that parameter. So at last, I decided to not use numpy and re arranged my code.

    • @wartem
      @wartem Před rokem +1

      Which numpy function was it?

    • @kcvinu
      @kcvinu Před rokem +1

      @@wartem numpy.ctypeslib.as_array(obj, shape=None)

    • @wartem
      @wartem Před rokem +1

      @@kcvinu Idk, but the shape of an array can be defined as the number of elements in each dimension.
      The parameter shape in your example is an iterable (tuple probably), used like this in _ctype_ndarray: "for dim in shape[::-1]:"
      You don't need the second parameter, shape, if converting from a ctypes array. It's needed when converting from a ctypes POINTER.

    • @kcvinu
      @kcvinu Před rokem

      @@wartem I have a ctype pointer which is pointed to an array of 9 c_ulongs. So I think I need the shape param. But without knowing what is shape, it is impossible to use that function. If it's the element count, then I have a value of 9. If it's the dimension of the array, then I have a value of 1. That's why I said, the docstring sucks.

  • @hlubradio2318
    @hlubradio2318 Před 2 měsíci

    Good old Turbo Pascal

  • @atulkumaryadav790
    @atulkumaryadav790 Před rokem

    return type is not working for me, still I can retrun other data type without any issue

    • @Indently
      @Indently  Před rokem

      Yes, Python works like that

    • @atulkumaryadav790
      @atulkumaryadav790 Před rokem

      @@Indently thanks, I did figured it out later. However, it's good for readability. Thanks again

  • @ThisRussellBrand
    @ThisRussellBrand Před 5 měsíci

    in number 3, why is it float rather than `float[]`

    • @dragweb7725
      @dragweb7725 Před 3 měsíci

      a float is not a container type, it cannot contain other objects of different types

  • @hlubradio2318
    @hlubradio2318 Před 2 měsíci

    Nice I didn't realize print takes *args

  • @Maegtur
    @Maegtur Před 2 měsíci

    "So that you can reuse them"

  • @gedtoon6451
    @gedtoon6451 Před rokem

    At 3 mins into the video you pass a number of integer parameters to a function that has a type hint of float. You did not explain that parameters with a type of float will happily accept integers as well.

    • @Indently
      @Indently  Před rokem

      True, but that's something you would learn in a video dedicated to type hinting.

  • @Spiderfffun
    @Spiderfffun Před rokem

    Sometimes I need the global functions, idk why they are so bad
    spaghetti code

  • @mzakyr342
    @mzakyr342 Před rokem

    Hey second or third probably

  • @PauloOrtolanCinemaniaco
    @PauloOrtolanCinemaniaco Před 2 měsíci

    So, some years ago I implemented a decorator to a project. It was pretty cool, but I neeeded to expand my system and did not have the time to make the proper change. And then I done a type variable decorator. Yeah, don't ever do this. This python system died due to main project evolution. I learned not to make this again.