6 CLEAN Tips To IMPROVE Your Python Functions

แชร์
ฝัง
  • เผยแพร่เมื่อ 8 มิ.ย. 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

ความคิดเห็น • 76

  • @dragweb7725
    @dragweb7725 3 หลายเดือนก่อน +13

    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 3 หลายเดือนก่อน +3

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

    • @saaofficial5415
      @saaofficial5415 2 หลายเดือนก่อน +1

      How about "sort_descending()" 😊

    • @cerealport2726
      @cerealport2726 29 วันที่ผ่านมา +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 ปีที่แล้ว +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 ปีที่แล้ว +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

  • @MechMK1
    @MechMK1 ปีที่แล้ว +40

    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 3 หลายเดือนก่อน

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

    • @HansStrijker
      @HansStrijker 2 หลายเดือนก่อน

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

  • @legr4ndk891
    @legr4ndk891 2 หลายเดือนก่อน +1

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

  • @SP-db6sh
    @SP-db6sh ปีที่แล้ว +5

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

  • @fernandomassey3140
    @fernandomassey3140 3 หลายเดือนก่อน +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

  • @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 :)

  • @fredflintstone8048
    @fredflintstone8048 7 หลายเดือนก่อน

    Excellent advice. Thank you for sharing.

  • @whkoh7619
    @whkoh7619 ปีที่แล้ว

    Great intermediate level tips! Thanks

  • @ShivaniSingh-ce6vb
    @ShivaniSingh-ce6vb ปีที่แล้ว

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

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

  • @master_sergik
    @master_sergik ปีที่แล้ว

    Very useful tips, thanks 👍

  • @hlubradio2318
    @hlubradio2318 หลายเดือนก่อน

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

  • @felicytatomaszewska2934
    @felicytatomaszewska2934 2 หลายเดือนก่อน

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

  • @muntadher8087
    @muntadher8087 ปีที่แล้ว

    Useful information thanks

  • @fullstackspiderman
    @fullstackspiderman 3 หลายเดือนก่อน

    @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 ปีที่แล้ว

    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.

  • @yeahnick4260
    @yeahnick4260 3 หลายเดือนก่อน

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

  • @judithlee7989
    @judithlee7989 ปีที่แล้ว

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

  • @littledonkey4925
    @littledonkey4925 ปีที่แล้ว

    Hi, nice TH-cam 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.

  • @arthurarashbricenoheidari2858
    @arthurarashbricenoheidari2858 10 หลายเดือนก่อน

    i loved your videos thanks a lot man

  • @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 3 หลายเดือนก่อน

      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.

  • @RobinZuFALL
    @RobinZuFALL ปีที่แล้ว

    Where can i get that white python hoodie?

  • @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 👍

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

  • @behnamheydarian9569
    @behnamheydarian9569 9 หลายเดือนก่อน

    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 3 หลายเดือนก่อน

      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 2 หลายเดือนก่อน

    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

  • @hlubradio2318
    @hlubradio2318 หลายเดือนก่อน

    Good old Turbo Pascal

  • @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)

  • @PanduPoluan
    @PanduPoluan ปีที่แล้ว +1

    I see you using PyCharm. Man of class 👍🏼

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

  • @hlubradio2318
    @hlubradio2318 หลายเดือนก่อน

    Nice I didn't realize print takes *args

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

  • @Maegtur
    @Maegtur 2 หลายเดือนก่อน

    "So that you can reuse them"

  • @ThisRussellBrand
    @ThisRussellBrand 4 หลายเดือนก่อน

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

    • @dragweb7725
      @dragweb7725 3 หลายเดือนก่อน

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

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

  • @Spiderfffun
    @Spiderfffun ปีที่แล้ว

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

  • @PauloOrtolanCinemaniaco
    @PauloOrtolanCinemaniaco 2 หลายเดือนก่อน

    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.

  • @mzakyr342
    @mzakyr342 ปีที่แล้ว

    Hey second or third probably