Should I define functions inside or outside of main()?
Solution 1
I would discourage defining functions inside of main()
, especially if you have multiple files in your Python script. Any function B
defined inside of function A
cannot be used by anything outside of function A
, severely limiting its usability. Functions defined inside main()
cannot be imported elsewhere, for example.
Defining functions inside of main()
lets you easily override other functions you may have written elsewhere that have the same name, but the instances where this is really useful are few and far between, and you should not be doing it as a general practice. Overall there are many more reasons for defining functions outside of main()
than there are for defining them inside, and if you're learning Python that's definitely how you should handle it.
Solution 2
If you define a function inside of the main function, you won't be able to use it from the outside. Here is an example:
def outer():
print "outer function"
def main():
def inner():
print "inner function"
inner()
if __name__ == "__main__":
main() # outputs: "inner function"
outer() # outputs: "outer function"
inner() # fails!
Comments
-
chishaku almost 2 years
After reading the following, I think I understand the value of wrapping even the simplest of scripts in a main() function.
Should I define all my functions inside or outside main()?
Is there a right or wrong way? What are the advantages and disadvantages of both approaches?
-
Dietrich Epp almost 10 yearsDefine functions where they make sense. Usually that place is at the top level, or inside a class definition.
-
miindlek almost 10 yearsIf you define a function inside the main function, you aren't able to use it from the outside.
-
Two-Bit Alchemist almost 10 yearsI don't think you do understand the value of it. It's not the
main()
function so much as theif __name__ == '__main__'
guard that provides most of the value discussed in those posts, and that in turn centers around being able toimport
stuff from your scripts. If you put your other functions insidemain()
, you are losing exactly that value.
-