Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 1268

Python • Re: breaking my code into separate files

$
0
0
Using separate files to group functions and classes in a logical way is always good - and keeps source files a manageable size for future enhancement. I try to keep files under 1000 lines max, usually much less if I can.

The main thing you want to avoid is "back-importing" stuff... i.e.: having two files that import stuff from each other. Imports should usually only be one direction, so that you don't run into issues with ordering, etc. Note, you can also get into circles that cause the same issue - where an imports from b, b imports from c, and c imports from a, etc.

If you DO get into a circle, the back-import will only be able to access stuff that's already defined in the source file when the import happens. This is hard to describe, but... something like this:

File a:

Code:

def a():return "this was a"import bdef c():return "this was c"
file b:

Code:

import adef b():return "this was b"a.a()# this will worka.c()# this will  fail - undefined when file a was imported
Generally, I structure the main file to be fairly simple, but controlling the startup of the program, and put all the other logic elsewhere. If you use simple examples like the above to work through your issues, it'll help you understand it all.

Lastly - Python convention says you should have all your imports at the top of your file. So that precludes EVER using a back-import like above because it'll always fail.

Statistics: Posted by MadCow42 — Thu Dec 14, 2023 2:20 pm



Viewing all articles
Browse latest Browse all 1268

Trending Articles