Python Forum

Full Version: Proper Layout of Code Question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Is there a 'standard' or 'preferred' way of coding in Python when coding functions?

Should the functions be listed in order they are called from top to bottom? Bottom to top? For example, is this ok or should fun1 be listed first because it's used first?

def fun1:
do something

def fun2:
do something

print('hello')
fun2()
fun1()

new to Python..be gentle! Big Grin
In my experience there is no unwritten rule that states that you have to order in a certain way. But there are however some clever tricks to structure your code.
If you would start with object oriented Programming (OOP) you would categorize your methods by set-methods, get-methods, methods of a certain kind (calculation, visualization, ...), abstract-methods, static-methods, underscore-methods, ...
For imports it is useful to order the imports by project-external and project-internal imports and inside of this order alphabetically. And a similar ordering can be done for the functions. you could order them alphabetically in general, you could order them by their purpose (visualization, calculation, file operations, ...) and inside of each topic you could order them alphabetically.
But you could also order them by the order they are called, but I prefere the ways described above, it is way easier to find anything in there :D
There is only one rule that the computer itself is giving you. When we write functions we need to make sure that the function is declared before its usage outside of other functions:
def f1():
   pass

def f2():
    pass

f1()
f2()
is definitely fine.
def f1():
f2()

def f2():
pass

f1()
f2()
[/python]
is fine as well. But:
def f1():
pass

f1()
f2()


def f2():
pass
[/python]
will not be accepted by the interpreter, since the function f2 is called before it is defined.

So in a nutshell, I often see it as an individual choice, but that is how I do my coding. Maybe someone has a different experience :)
Great! Thanks for the help!