Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

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!

So main is just an entry point not usually a good place for lots of methods. Best practice would be to separate functionality among classes. It also makes it easier to manage in the future if changes need to be made. Hope this helps.

Hello and good question.

Just by "being use to" main() functions, many Python programmer with former experience in C++, Java, and C# love to use def name = "main" for of some sort. While "old school" programmers like this, Python is a very versitile, free form programming (actually it is a scripting language) what it does not need a main function.

If you were to make a basic calculator program, you can just make a function called "calc", and Python will be happy. I have made a GUI Vector Calculator w/o a "main" function, so there is Zero need.

def calc(x, y): sum = x + y return sum

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top