5 Tips To Organize Python Code

Поделиться
HTML-код
  • Опубликовано: 19 дек 2024

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

  • @wannabedev2452
    @wannabedev2452 2 года назад +229

    I have outgrown the difficulty of what you teach but i still come back time to time because your content is what taught me most of what i know

  • @Richard_GIS
    @Richard_GIS Год назад +44

    The correct order for pep compliance is (see style guide 'Imports'):
    1: Standard library imports.
    2: Related third party imports.
    3: Local application/library specific imports.

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

      you are correct

    • @live_destin-3408
      @live_destin-3408 6 месяцев назад +4

      I’ve been doing this for so long without knowing it was an actual named standard. It’s just logical

  • @ppolleunus
    @ppolleunus 11 месяцев назад +34

    It's not __init__.py that makes a package. It's even not required anymore in Python 3.x. It's just having a folder. Basically, package = folder and module = file.

  • @sobysonics
    @sobysonics 10 месяцев назад +3

    1) use module and package: module is individual python file, package is directory with many python modules; package requires __init__.py - which makes folder the package; whatever is in init, it will be run
    2) one class in one file (may be exceptions)
    3) group related functionality together
    4) separate utility and helper functions
    5) organize import statements

  • @v0nd3rB0y
    @v0nd3rB0y 2 года назад +17

    About organize imports, pep8 recommend use 1. standard library imports
    , 2. related third party imports, 3. local application/library specific imports . Anyway great video Thanks!

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

      And this can be achieved automatically with tools like isort or ruff (my linter of choice) + pre-commit git hooks

  • @YouTubeSummariser
    @YouTubeSummariser Год назад +18

    Thank you for creating this video on organizing Python code. It may be useful to others who want to improve the readability and maintainability of their code. Here are the 5 key points of the video.
    1. Use modules and packages to better organize Python code.
    2. Place each class in an individual file using Pascal case.
    3. Group related functionality together in packages.
    4. Place all utilities in a single file or package.
    5. Organize import statements by third party, built-in, and local files.

    • @live_destin-3408
      @live_destin-3408 6 месяцев назад +1

      It’s crazy how your comment sounds so much like chat gpt to me. I think I’ve been using gpt to much lately, because I’ve become paranoid that everything around me was written with the bot; when in reality, people are just having good grammar

    • @Leadbraw
      @Leadbraw 2 месяца назад

      ​@@live_destin-3408...

  • @simoneisenschink5269
    @simoneisenschink5269 Год назад +7

    Wow, this is exactly what i was searching for when improving in coding but didn't learn it from scratch just somewhere in between. Thank you so much!

  • @fabianstargalla
    @fabianstargalla 2 года назад +20

    Slowly I start to understand how GitHub Projects work. I must say as a "advanced" beginner who has just finished learning native Python it's pretty intimidating to see such big Projects and not understanding a single thing even though I'm not actually struggling with the Python part but I guess that's a thing you have to get used to :D
    Great video Tim, thank you very much ❤

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

      I'm in the same boat. Tail end of my python course, which includes an "advanced python" section. What intimidates me is all the ways to potentially do 1 thing. Seeing the varying syntax freaks me out. What helped is getting organized, thinking in algorithms, and accepting that the web will answer all my syntax questions easily.

  • @MrRockus
    @MrRockus Месяц назад

    A useful video, it's one thing to be able to code in Python, but to manage your files is just as important.

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

    This vid was exactly what i need to finish my project, thank you so much!

  • @kirollssabri4651
    @kirollssabri4651 2 года назад +13

    Every time i see a notification from your channel i feel so happy and excited to learn something new❤️

  • @DanielCordey
    @DanielCordey 2 месяца назад

    I totally agree with all of your tips. Especially the No 2; which I also practice when I write C code... since 1990.

  • @crazycat664
    @crazycat664 2 года назад +3

    Feels like this guy knows everything I need to know in python

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

    Just starting my journey here and I am enjoying this content from over the years. Great stuff Tim

  • @eliasebner3595
    @eliasebner3595 2 года назад +6

    OMG, THIS WAS ACTUALLY SO USEFUL. Thanks a lot, really learned a lot.

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

    Great content, totally agree on pretty much everything.
    For Utils I would add a little thing: I usually recommend not to do it cause 1. junior dev would over use it and 2. It doesn’t help to know what’s inside. So for me, it is on very last option.

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

    Because of this guy, I learned how to organize my code 👌

  • @ToddVanyo
    @ToddVanyo 11 месяцев назад

    You can have the import statements auto sorted by using the isort tool, which formats the imports consistently.
    Available as a formatter in multiple LSPs.

  • @gilbertjizz4811
    @gilbertjizz4811 2 года назад +31

    One class per file makes your code very organized, I agree. However, if two classes are very related it is okay to put them together

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

      I'd say if you have a hierarchy of classes (for example 2-3 classes that inherit from an abstract class) you should group them together in a single file, unless they're too large, but that probably means you are breaking a SRP rule

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

      ​@@ThatOpinionIsWrongWhat would you say about class composition, then? If you have one class that is used strictly and extensively inside of a parent class, with no inheritance concerns involved, would it make sense to put the child class definition in the same file as its parent class definition?

    • @carnap355
      @carnap355 11 месяцев назад

      Honestly if you can get away with one class per file you are not using OOP enough

  • @taylormayhew369
    @taylormayhew369 7 месяцев назад +1

    You are the GOAT ❤

  • @futurism010
    @futurism010 2 года назад

    No words to explain the contents you made! Just Amazing.

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

    Absolutely fantastic! Thank you :)

  • @danielsehnoutek2016
    @danielsehnoutek2016 5 месяцев назад

    amazing tutorial, what a legend :D

  • @davideschreiber2821
    @davideschreiber2821 2 года назад

    Here's one little compliment you might not have got before. I do think your tutorials are among the very best on RUclips, but having seen some others, I am also very grateful you don't try to be cute or humorous or pumped with enthusiasm. I don't think humour comes easily to programmers (Socratica is an exception), and those who try it generally just sound lame. You give us the straight goods without making us squirm or groan. I really appreciate it.

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

    I been trying to work this out for the last 3 days,.... you are a legend but it makes my head hurt,.. thank you though.

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

    awesome content and is nicely presented. Thanks.

  • @dareal738
    @dareal738 2 года назад

    you post stuff as i search for it, why, ily so much

  • @ramneekkaur9645
    @ramneekkaur9645 2 года назад +1

    Thanks Tim 👍🌟

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

    I like to do built-ins first, then third party, then local libraries. Then I do initializations and globals, like input_dir = "". I guess what's important is having a system.

  • @christianm4906
    @christianm4906 3 дня назад

    I agree to keep classes in individual files.

  • @leaoaugusto
    @leaoaugusto 2 года назад

    Thank you Tim! God bless you!

  • @kosmonautofficial296
    @kosmonautofficial296 2 года назад

    Great video thanks so much! I have been using modules but not local packages thanks!

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

    Though I know this, I still think these tips are important, and I know these not from courses but from reading coding books. Thanks, for me, these are great helps too.😁😁😁

  • @brianrichard903
    @brianrichard903 2 года назад

    Hi Tim! great video , i enjoyed it and now i feel like i can easily take on python

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

    Excellent tips.. thanks!

  • @gJonii
    @gJonii 2 года назад +5

    I find this "separate helper functions" to be an antipattern. Functions that are helpful to one module should be in that module. Functions that are helpful in multiple places are a sign that some module should be doing that task for you already. By these tips you're making it harder to write proper code.
    Same with "unrelated things together", it's an antipattern of making a mess.
    Also, one file = one class sounds almost right but it promotes OOP style thinking, which in itself is kind of an antipattern. I'm not really sure what's the best way to go about it myself, but my own rule of thumb is to chop things up into modules and files to provide a single concept to user of that module or file. It's almost the same, except, a class isn't that good approximation of a concept. You'd be basically falling for OOP trap by forcing your concepts into class-shaped boxes.

    • @lawrencedoliveiro9104
      @lawrencedoliveiro9104 2 года назад

      Functions that are useful in multiple places are a sign of effective code reuse.

    • @gJonii
      @gJonii 2 года назад

      @@lawrencedoliveiro9104 If the functions don't have clear domain where they operate in, it is to me the antipattern. If you can't name the common thing that all these parts of your program share, beside "helper", you're in a world of hurt if any of the parts coupled through "helper" change or want to be refactored, since there is no context for "helper" stuff to give you any expectations about which way things actually should be, why are things coupled, or even which things are coupled.
      It works if you get it right while you still had the entire program inside your head while making that. Anyone coming afterwards is going to be locked out of making any changes because aside from going through the program line by line to verify how the helpers are used, there's no way for you to know if any change is possible, reasonable, and what it will break.
      Contrast this with having helpers be tied to the module they're used in. You need to understand one module to make changes to helper functions. They're also now coming with context, since you don't need to name helpers, parameters, comments etc in a general non-specific manner, but rather you can have those helpers have very clear purpose in the context of the module. You making changes to helpers is now in terms of what makes sense in context, specifically for your module and the business logic surrounding it, and thus you also understand from changes what consequences it has.
      If you need same helper function in three different modules, I'd any day of the week that same helper function three times, once per module, and treat it as internal to each module.

    • @lawrencedoliveiro9104
      @lawrencedoliveiro9104 2 года назад

      @@gJonii Look at, for example, the built-in integer operations. Do they have a “clear domain where they operate in”? Or are they in fact widely used in a lot of different code?

    • @gJonii
      @gJonii 2 года назад

      @@lawrencedoliveiro9104 built-in integer operations? You have the domain in the name, it's integers. Them being used in projects is confusing developer of the built-in interface, and developers of python programs.

    • @lawrencedoliveiro9104
      @lawrencedoliveiro9104 2 года назад

      @@gJonii So you feel Python shouldn’t have such operations, because you find them “confusing”?

  • @jenjapa
    @jenjapa 2 года назад

    Great video, very useful. Thanks.

  • @itssuperbaby2979
    @itssuperbaby2979 2 года назад

    this is not related to your video but the cat in the intro was so cute :D

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

    WASHHHHHHHHHHHHHHHHHHH SOPHIE IS SO CUTE! 😻😻😻

  • @AddisChess16985
    @AddisChess16985 2 года назад

    Nice video, Tim!

  • @jgojiz
    @jgojiz 8 месяцев назад

    If I'm inside a folder, wanting to call functions or classes from another folder, same project, how do I do that? Does this structure only work with main files not inside folders?

  • @cristinocanga
    @cristinocanga 2 года назад

    Hey Tim, i just wanted to say that you didn't add the other videos to the intermediate python list
    Future topics:
    9. Collections: orderedDict
    10. Collections: defualtDict
    11. docstrings
    These are missing lol
    Big fan

    • @Brickkzz
      @Brickkzz 2 года назад

      Isn't dict ordered in recent python versions?

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

    I wanted to do a class for file in one package but all of them need to import one file and when I try to import the classes from outside the package it gives an error cause of the import

  • @balazsh2
    @balazsh2 2 года назад +11

    I think "local imports last" should be a hard rule, in case you're overwriting built-in functions or classes you should never load built-in modules over it

  • @funtocode5904
    @funtocode5904 2 года назад

    GREAT VIDEO! btw small youtuber here!

  • @zyhon881
    @zyhon881 2 года назад

    Thank you very much. Very useful tips. Just subscribed to ProgrammingExpert.

  • @MeHdi.fz28
    @MeHdi.fz28 Год назад

    thanks that was very helpful

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

    THANK YOUUUUUUU! I am doing a Python project for college and this is exactly what I needed.

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

    Its super niceee 🎉

  • @schedarr
    @schedarr 2 года назад

    what is this star in snowflake_time function definition?

  • @HDelport8
    @HDelport8 2 года назад +1

    I'd hate to break the 69 comments but,
    Tip one is a personal game changer that I should have learned in my years of full stack dev studies. I feel like I just learned a basic...

  • @inspisiavideos8542
    @inspisiavideos8542 2 года назад +2

    Tech With Tim I kept making a lot of projects on my portfolio about React, Python and APIs. I just got hired! My first job in tech and it’s ove $100K at an internet company. The thing is I won’t see any of the languages I worked hard to learn. If anything, at my job I will see some html and css and that’s it. Other than that, I’m looking at presentation for ads, review analytics with google analytics and make some calls to the employees working at the company’s stores about the updates. Don’t get me wrong. I’m happy I am making 117k but I sometimes think that if I don’t practice coding I might forget and who knows I might need it in the future. BTW I don’t want to go through interviews again. It was horrible many companies told me no and thank goodness this one told me yes because I was 2 months with no job down to my last $200 and finally I got in but I feel at the long run I might become lazy. What do you think? Do you think it’s probably good I don’t have to code too much?

    • @mrman880
      @mrman880 2 года назад +1

      Definitely keep coding fresh in your head.

    • @neuron8186
      @neuron8186 2 года назад +2

      i suggest try doing one leetcode question everyday or once in every 2-3 days because you have a job starting side project can be hectic also leetcode will help you in future if you ever thought of changing job

    • @inspisiavideos8542
      @inspisiavideos8542 2 года назад +1

      @@neuron8186 Right now I’m still on training but they already told us what I’ll be doing. That’s the thing, my job is multiple things. It’s more like graphic designing, analytics, see code but only html and css and call people that work at the stores. But my title says Analytical Software Developer. Again, I know I shouldn’t complain. Because from last year from June to December I had an internship as an engineer looking at React and cypress and one of the head of Engineers told me once that he’s always worried about deadlines because if anything happened before or during production the blame was on him. I really feel I shouldn’t complain because I didn’t work for 2 months it’s just that in my mind I always thought on building cool stuff. Again I don’t have stress at my job and feel happy for the pay but I sometimes think I have so much more potential

    • @spaghettiking653
      @spaghettiking653 2 года назад

      @@inspisiavideos8542 Always improve yourself; if anything, even if in terms of career, you aren't using what you learnt, you can always advance on your own personal terms. Make something massive, something impressive that you can call yours. Maybe in a new language. Hope you're still doing well at your job.

  • @georgehammond867
    @georgehammond867 2 года назад +1

    great tips. but would be great to do more on point #1 - Use Modules and Packages.

  • @Pankaj-Verma-
    @Pankaj-Verma- 11 месяцев назад

    Thanks 👍

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

    is ok to define all required function in single python file ?

  • @bonkaiblue7906
    @bonkaiblue7906 8 месяцев назад

    Cant you just put your imports in an import package called imports? then you have one import at the top if your main that calls all your imports? & they can be organized further in there.

  • @elamandeep
    @elamandeep 2 года назад +1

    Hey tim , please make video how to read programming document??

  • @ewetoobie
    @ewetoobie 2 года назад

    how would this change with pygame? imports & such seem more complicated, also pygame.init() seems to need to be in each module, etc. Any tips?

  • @andressaldarriagajordan6526
    @andressaldarriagajordan6526 2 года назад +5

    I prefer to use relative import (from [dot]package import this) as it makes more clear we are importing a local package and not, maybe, a standard library's module with the same name

    • @balazsh2
      @balazsh2 2 года назад +1

      Relative imports can get messy though when you have to import files across your separate modules and have to pay attention to how many periods you write depending on how deep you are in your directory tree. Separating your standard library, third-party and local imports with newlines work just as well but keep the consistency of your code. Also it's bad practice to give your directories the same name as existing libraries, this is what directory naming conventions are for

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

    Thanks!

  • @alchenerd
    @alchenerd 2 года назад

    So theoretically, malicious code can be be injected into __init__.py and do anything, like, say, append itself to all __init__.py on the host?

  • @ismail.dalhatu
    @ismail.dalhatu 2 года назад +1

    Sophie out there! 🤦‍♂️😅

    • @ismail.dalhatu
      @ismail.dalhatu 2 года назад

      @♜ Pinned by Tech With Tim ridiculous!

  • @jomy10-games
    @jomy10-games 2 года назад

    What VS Code theme do you use?

  • @brianferrell9454
    @brianferrell9454 2 года назад

    needed this

  • @mahshidheshmati3389
    @mahshidheshmati3389 2 года назад

    Can you take a course for computer olympiad topics?🙏

  • @arthuradriansens3291
    @arthuradriansens3291 2 года назад +1

    Hi Tim, your videos are super helpful! Can I ask a question please: how can you enable execution time in vs code? Thanks!

    • @splashoui3760
      @splashoui3760 2 года назад

      You can use time module in python and print the difference between end time and start time.

  • @murphygreen8484
    @murphygreen8484 2 года назад

    Hey, I was just searching for something like this. What are the chances?

  • @harveykyle3690
    @harveykyle3690 2 года назад +1

    wow look at the cat on the intro :D

  • @educateyourselfdaily3196
    @educateyourselfdaily3196 2 года назад

    Hey Tim, will you 💞 know me which software you are using for video 📷 editing Please...

  • @keaganhurter2550
    @keaganhurter2550 Месяц назад

    we came Sophie, we stayed for the tips

  • @planktonsgaming8232
    @planktonsgaming8232 2 года назад

    Your just legend

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

    There are a lot of things in pep8 that I disagree with. Why not name the file exactly as the classname? That way, if a file begins with a capital letter, you know it contains a class and you know exactly what that class is called. If a file begins with a lowercase letter, you know it's a script without a class. I use this convention for PHP code and it works great.

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

      How do you name files that both are standalone scripts and also contain classes you import elsewhere?

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

      @@samwilson5544 personally I wouldn't have that. Those would be separate files. Too hard to find things if a file has too many different things in it.

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

    I need to learn to structure code properly .

  • @educateyourselfdaily3196
    @educateyourselfdaily3196 2 года назад

    Hey Tim 👍

  • @MrTien-yq6cj
    @MrTien-yq6cj 2 года назад

    Love this

  • @lam-thai-nguyen
    @lam-thai-nguyen 11 месяцев назад

    thank you

  • @zZMazeZz
    @zZMazeZz 2 года назад

    great videos

  • @JakobJensen-y3d
    @JakobJensen-y3d 11 месяцев назад

    The "import" in "__init__" does not work as I've would expect it.
    If the statements in __init__ are run when we import the module, then I would expect that when we in `__init__` have `from forces import Forces` then we should be able to just used `Forces` right away in `main.py` and not have to import it first (since the "import" part is run in the "__init__").
    So, just to make sure I've understood it correctly; import in `__init__` does not actually import, but "moves" the imports to the main-module such that they can be imported directly from the main-module and not the submodule.

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

    sophie the cat is adorable

  • @melissaleigh3013
    @melissaleigh3013 2 года назад

    Thanks

  • @pawulo6953
    @pawulo6953 2 года назад

    Could you make a video about cat role in the programmer's life?

  • @arjix8738
    @arjix8738 2 года назад +1

    My import order is based on the length of the line, and in descending order

    • @spaghettiking653
      @spaghettiking653 2 года назад

      Ooh interesting, I usually do it in ascending, and also with all "import" lines coming before all "from import ..." lines...

  • @aayushpatil7514
    @aayushpatil7514 2 года назад

    Can you make one for golang? That would be helpful 😃

  • @nowifi3266
    @nowifi3266 2 года назад +1

    Do I have to import a module (such as Pygame) into each module/package __init__ file that I create myself?

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

    After tip 2 I was expecting tip 3 to be "switch to coding in Eclipse"

  • @umeshlab987
    @umeshlab987 2 года назад

    Sophie is cute
    @Tech with Tim how many cats do you have?

  • @nowyouknow2249
    @nowyouknow2249 2 года назад

    Does Sophie code too 😆?

  • @JLSXMK8
    @JLSXMK8 2 года назад

    0:10 What breed is she?! Too precious.

  • @devsutong
    @devsutong 2 года назад

    how to import packages that is not on the sane directory? I've tested relative path but it's not working

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

    Nice cat sophia

  • @beatmarsgo6972
    @beatmarsgo6972 2 года назад

    I saw the cat 🐱😳

  • @Betabdullah
    @Betabdullah 2 года назад

    Allah razı olsun

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

    I give you like for Sophie🥰😄...

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

    I been doing it all wrong I only knew about camel case,... 😢

  • @pravachanpatra4012
    @pravachanpatra4012 2 года назад

    TIM CAN MAKE Django Tutorials

  • @mohmedbadr1947
    @mohmedbadr1947 2 года назад

    whats peppe et?

  • @computerrcat870
    @computerrcat870 2 года назад

    i am more focused on the cat

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

    Single class = single file isn't controversial... convention is from S.O.L.I.D..

  • @pravachanpatra4012
    @pravachanpatra4012 2 года назад

    Tim can make more DJANGO tutorials?

  • @KosaQDev
    @KosaQDev 2 года назад

    Second

    • @KosaQDev
      @KosaQDev 2 года назад

      @♜ Pinned by Tech With Tim dont worry be ddos