6 CLEAN Tips To IMPROVE Your Python Functions

Поделиться
HTML-код
  • Опубликовано: 21 июл 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

Комментарии • 77

  • @dragweb7725
    @dragweb7725 4 месяца назад +16

    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 4 месяца назад +5

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

    • @saaofficial5415
      @saaofficial5415 3 месяца назад +1

      How about "sort_descending()" 😊

    • @cerealport2726
      @cerealport2726 2 месяца назад +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.

  • @MechMK1
    @MechMK1 Год назад +42

    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 Год назад +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 Год назад +6

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

    • @kellymoses8566
      @kellymoses8566 4 месяца назад

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

    • @HansStrijker
      @HansStrijker 3 месяца назад

      @@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.

  • @fernandomassey3140
    @fernandomassey3140 4 месяца назад +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!

  • @davidl3383
    @davidl3383 Год назад +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

  • @jakedeschamps4454
    @jakedeschamps4454 Год назад +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 Год назад +3

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

    • @jakedeschamps4454
      @jakedeschamps4454 Год назад

      @@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 Год назад +12

      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

  • @SP-db6sh
    @SP-db6sh Год назад +6

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

  • @ashersaipe
    @ashersaipe Год назад +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 :)

  • @legr4ndk891
    @legr4ndk891 3 месяца назад +1

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

  • @fredflintstone8048
    @fredflintstone8048 9 месяцев назад

    Excellent advice. Thank you for sharing.

  • @WhyNotProgram
    @WhyNotProgram Год назад +1

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

  • @ShivaniSingh-ce6vb
    @ShivaniSingh-ce6vb Год назад

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

  • @whkoh7619
    @whkoh7619 Год назад

    Great intermediate level tips! Thanks

  • @fullstackspiderman
    @fullstackspiderman 4 месяца назад

    @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?

  • @master_sergik
    @master_sergik Год назад

    Very useful tips, thanks 👍

  • @castlecodersltd
    @castlecodersltd Год назад

    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  Год назад +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 Год назад +3

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

    • @volbla
      @volbla Год назад +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.

  • @RobinZuFALL
    @RobinZuFALL Год назад

    Where can i get that white python hoodie?

  • @judithlee7989
    @judithlee7989 Год назад

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

  • @littledonkey4925
    @littledonkey4925 Год назад

    Hi, nice RUclips 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 Год назад +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.

  • @muntadher8087
    @muntadher8087 Год назад

    Useful information thanks

  • @jonathanlloyd8688
    @jonathanlloyd8688 Год назад

    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?

  • @fluffykitties9020
    @fluffykitties9020 Год назад +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 Год назад +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 4 месяца назад

      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.

  • @arthurarashbricenoheidari2858
    @arthurarashbricenoheidari2858 Год назад

    i loved your videos thanks a lot man

  • @kelvenlim9283
    @kelvenlim9283 Год назад +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 Год назад +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  Год назад +1

      A truly informative comment, thanks Anthony!

    • @samueljehanno
      @samueljehanno Год назад

      ​@@anthonydesouza9983 👍

  • @yeahnick4260
    @yeahnick4260 4 месяца назад

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

  • @hlubradio2318
    @hlubradio2318 3 месяца назад

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

  • @behnamheydarian9569
    @behnamheydarian9569 10 месяцев назад

    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 4 месяца назад

      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

  • @haarissultan8866
    @haarissultan8866 4 месяца назад

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

  • @yapnog603
    @yapnog603 Год назад +2

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

    • @KevinArellano
      @KevinArellano Год назад

      It's on pycharm.

    • @constantinschultz7253
      @constantinschultz7253 Год назад +2

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

    • @brainsmoothheadempty
      @brainsmoothheadempty Год назад +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 Год назад +1

      Font ligatures

  • @felicytatomaszewska2934
    @felicytatomaszewska2934 3 месяца назад

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

  • @JordanMetroidManiac
    @JordanMetroidManiac Год назад

    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  Год назад

      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 Год назад

      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)

  • @atulkumaryadav790
    @atulkumaryadav790 Год назад

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

    • @Indently
      @Indently  Год назад

      Yes, Python works like that

    • @atulkumaryadav790
      @atulkumaryadav790 Год назад

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

  • @kcvinu
    @kcvinu Год назад +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 Год назад +1

      Which numpy function was it?

    • @kcvinu
      @kcvinu Год назад +1

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

    • @wartem
      @wartem Год назад +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 Год назад

      @@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.

  • @ThisRussellBrand
    @ThisRussellBrand 6 месяцев назад

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

    • @dragweb7725
      @dragweb7725 4 месяца назад

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

  • @PanduPoluan
    @PanduPoluan Год назад +1

    I see you using PyCharm. Man of class 👍🏼

  • @hlubradio2318
    @hlubradio2318 3 месяца назад

    Good old Turbo Pascal

  • @hlubradio2318
    @hlubradio2318 3 месяца назад

    Nice I didn't realize print takes *args

  • @gedtoon6451
    @gedtoon6451 Год назад

    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  Год назад

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

  • @Maegtur
    @Maegtur 4 месяца назад

    "So that you can reuse them"

  • @Spiderfffun
    @Spiderfffun Год назад

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

  • @mzakyr342
    @mzakyr342 Год назад

    Hey second or third probably

  • @PauloOrtolanCinemaniaco
    @PauloOrtolanCinemaniaco 3 месяца назад

    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.