I learned from a similar question on imports that one should not mix "operational code" and import
(they should be at the top).
What is the consensus around defining functions in the middle of "operational code"?
I have a case where a function is used in just one place (it has to be a function) and having its definition close to that piece of code would make sense (all would be grouped together). It visually breaks the flow of the code, though.
Any advice from PEP? (I did not find anything relevant, as opposed to import
)
EDIT: the apparent trend in the answers is that it is not a nice thing to do, but unlike the import
case mentioned above there are no definitive directives (PEP for instance)
All code in a python script or module (which is basically the same thing - the difference being how it is used) is "operational code" one way or another. The clean way to structure a script's code is to have everything in functions - what you name "operational code" being in a "main()" function - and just have a call to that "main" function if the module is used as a script, ie:
# mymoduleorscript.py
import something
from somewhere import somethingelse
def somefunc(arg1, arg2):
# ...
def otherfunc(arga, argb):
# ...
def main(*args):
# "operational" code here
return status_code # 0 if ok, anything else if error
# only call main if used as a script
if __name__ == "__main__":
import sys
sys.exit(main(*sys.argv[1:]))
Note that this is not a "in my opinion" answer, but the officially blessed OneTrueWay of doing things.
Unless it's really necessary, i prefer to put all of it at the top of my script, since it makes finding them easier - more readable - and neater as well.
I think this starts to be pretty important if your code is going to be read by others, you don't want them to be confused when they want to see the functions, or how your code is operating.
Also, breaking down your program to smaller pieces, especially for long, long code is a good idea. When you have to deal with either part, you can do it quickly. So for me, the top is for declarations, and the bottom is for operational code. :)
I don't know why, but i feel like appending this here:
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With