Change language

5 Tips To Organize Python Code

5 Tips To Organize Python Code

in this video i will share with you five tips to better organize your python code these are not going to be life-changing theyre not going to have to do with software design and software architecture there are simple things that you can implement that make your code much more readable and easier to navigate with that said lets get into tip number one [Music] alright so my tip number one is to use modules and packages now a module is an individual python file a package is a directory containing multiple python modules this is the best way to organize your python code whenever youre working on a relatively large project you definitely want to utilize both of these things right now i will give you a quick two-minute tutorial on how they work if you want to learn more and learn more about software design in particular then check out my course programming expert dot io ill leave a link to it in the description you can use discount code tim if you are interested regardless lets have a look at this so here you can see that i have this physics package and what makes it a package is the fact that i have this init.pi file inside of it so whenever you want to make a package you do a directory you put some python modules whatever you want you dont have to have any but if you want some and then you put an underscore underscore in knit underscore underscore dot pi now this is a special file and ill talk about how it works in a second but this is what makes this folder here a package okay so now that ive done that from main.pi i can come here and say import and then just import the name of the directory itself now notice when i run the code here theres no error im able to import this successfully and lets have a look at something cool here when i go inside of init.pi and i run the code or i have print hello world now when i come to main.pi and i run this notice hello world prints out now i didnt print anything from here i just imported the physics package and what happens is whatevers inside of init.pi thats going to run exactly one time the first time that this package is imported so from my main file i import the package and then whatever is inside of here runs exactly once now the power of this is that you can do some initialization code inside of your package you also can import things from a nit.pi which then allows main.pi to import them without knowing whats inside of the package so youll see what i mean here but i have this class lets actually go with forces okay so i have this forces class so what i can do is go to init dot pi and i can say something like from dot and then forces import and then forces okay well continue to print hello world and now what this allows me to do is from main dot pi i can now say from physics import and i can import forces and the reason i can do that is because weve imported here now if i remove this line so lets actually remove it and try when i run this notice it says forces is not in the module fit or not on the package physics sorry cant find it lets clear that lets go back here lets re-import that now lets run and notice it prints out hello world but now i can also use forces if i want so i could say forces like this and when i initialize it it just prints something out so lets initialize it lets run and then i get hello world and forces so that is really the power of modules and packages you can put packages inside of other packages and what i was doing here in a net.pi is something called a relative import where i am importing from the current package thats what the single dot mean s the uh the forces file and then from the forces file im importing the forces class anyways that is tip number one use modules and packages dont be afraid to separate your code out if you have one large file containing multiple classes multiple functions all kinds of stuff that doesnt make sense to be in one place separate into multiple modules separate it into multiple packages and then write the appropriate import statements to bring everything into the file that you need alright so tip number two may be slightly controversial so let me know in the comments if you disagree with me of course theres exceptions to everything that im saying here and this is going to be to place a single class in a single file again there may be some exceptions some people may say do not do this but for me when im writing primarily object oriented style code in python i like to place each of my classes in an individual file so in this case i have an angular momentum class obviously its a very simple example just for the video and ive placed it in a file called angular underscore momentum now another thing to note here when youre naming files in python the convention is to do snake case so snake case with all lowercase letters you should not have any capitals in there and if you want to have a space do an underscore but when youre naming a class you want to have this in pascal case so pascal case mean s capital on the first word capital on all the other words no spaces and no underscores so it looks a little bit weird because this is different than the file name but thats the convention in python thats what you are supposed to do according to pep 8.

anyways that is what im saying for this tip place each class in an individual file i find this makes your code very organized very easy to find the different classes and if you need to use a class from another class then just import all right that is tip number two alright so for tip number three which is to group related functionality together im here on my organizations github page ill leave it in the description if you want to contribute to open source projects then please check this out all of the stuff here is done by volunteers i have not written a single line of code and this is all organized and facilitated through my discord server discord.gdg twt ill leave a link to the description we have like 33 000 members so please join that if you want to be a part of this and you can also ask some of the people who have set these repositories up hey how did you structure the code if youre curious about that anyways im going to go to this api directory here i dont know what a lot of this stuff is because again ive not written any of this code its all volunteers but im just going to show you how theyve kind of structured the different repositories and youll see how easy it is to navigate everything and how someone like me who again has really never looked at this before can easily figure out where all of the different code is so the tip was as a reminder group related functionality together so immediately when im looking here i see a bunch of random files these files are fine to just be in the main directory because theyre all kind of unrelated and since all these things are unrelated theyll all be in the same place so were grouping the unrelated things together which you know in turn groups related things together uh anyways that we have utils tests docs and then api so immediately we have four packages or four directories that are separating out the main things that we have in our application so when i go to utils i see that i get some utilities notice i have my init dot pi inside of here were importing a few things and saying all is equal to this another python convention i wont really talk about that then if i come here to test i have a bunch of different tests i have my test utilities so the utilities for the tests are in a separate uh i guess you could call this a package although it doesnt have the init.pi file but thats fine you can still kind of call it a package continuing we have our docs okay documentation here so we have an md file markdown file for how you actually run some of the different things here going back we have api inside of api we have models we have services we have versions if i go to services we have the different services if i go to versions we have a version v1 okay so this is where im getting at its not super complicated theres not a ton of stuff that you have to do just think logically about what stuff makes sense to be together and put it together in this case they thought we had api documentation tests and utils that was the main group of stuff okay all the stuff related to that goes inside of the package if theres more specific stuff within say the api within the docs we make a new package or folder for that and we are good to go alright so my next tip is a quick one and this is to place all of your utilities in a single place so either a single file or a single package now theres a lot of times when youre writing kind of helper functions or functions that dont belong in a certain class or belong in a certain file and you dont really know where to put them for example maybe you want to convert a date from the date time object to a string or maybe you want to you know figure out the distance between two points whatever theres some random kind of helper functions that again arent easily classified into a class or a file or some part that already exists in your application if thats the case what you want to do is create a utility package or a utility module if you only have say three or four functions that youre using and dump them all into there like i was saying before when you have stuff thats not related together all of the stuff thats not related you should put in one place because what relates it is the fact that its not related to something else i know thats a little bit backwards but i just want to show you here in this code base they have the utils package right and inside of utils we have things related to permissions these are going to be used in multiple places they dont make sense to be anywhere other than the permissions file right same thing with response we have stuff related to the response we have a json response class time.pi okay this is doing stuff with time snowflake time whatever i dont know exactly whats going on but the point is the way theyve named this and organized it its very easy for me to go in and see where the utilities are being used and that way theyre not clogging up different files and if i want to add something or change something i can do it all in one place in the utils package or utils file that was it for that tip lets move on to number five all right so my last tip for you here is to organize your import statements now i dont know if theyve done it exactly the way im going to recommend in this code base but i can already see that they have this being done decently and this becomes very important when you have a ton of different imports and a large project so youll see a lot of python files where you have like 20 imports 30 imports in this case we have 11 imports and its just really nice and easy when you actually organize and sort the imports so you can go in whatever style you want so long as youre consistent across your project what i like to do is import all of my third-party libraries first which is actually what theyve done here so theyre using fast api so they take all their stuff from fast api then from fake readies then from aio http then from logging although logging is actually a built-in module in python so i wouldnt put that exactly with all of this anyways i like to go third party imports then i like to go built in imports so something like os json logging stuff that you dont have to install thats built into python then i like to go with my local files or my relative imports so in this case these are all local files that theyve coded themselves utils.response api config and then lastly i like to alphabetically order my imports although that can be a little bit challenging sometimes because you have to ask how are you doing it alphabetically are you doing it by the name of the package for example or the name of the module are you doing it by what youre importing so that ones not as important anyways this just makes it really easy to quickly go in locate the different things that youre importing see if you need to change something and know what block youre going to add a future import to so again they havent done exactly like i would do it but this is pretty good they have all of their third parties then they have their built-ins i would put this one line down just to have third parties built in and then i have all of my local imports or relative imports so just to continue to test these guys and see if theyve been consistent here lets go into another file and okay so here i already noticed a few inconsistencies so these are local files then we have another local file then we have our built-in which is typing then we have our third-party module then we have a local file then we have another local file now maybe theyve organized it in this way for some reason that im not familiar with or that i just dont understand because again i dont write this code this is not my code base to maintain but what i would have done is swapped it around so it was in the order i said third party built-in and then your local files however again theres always exceptions and you can always make debates this is not a strict rule these are just tips that for me i find helpful and well hopefully they helped you with that said i will wrap up the video here if you guys enjoyed make sure to leave a like subscribe to the channel check out programming expert if you want to learn more about this topic and i will see you in another youtube video [Music] you

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically