Reputation: 1657
Can I write a python code with a bunch of functions but without a main function. The purpose of this script is for other scripts to import some of the functions from. I will call it setvar_general.py or something which will be imported by a series of other setvar_x scripts. While these setvar_x do more specific things, setvar_general does not do any thing other than providing building blocks. Therefore there is not need for defining a main function in setvar_general.py.
I guess it all comes down to the question "do I have to have main function"?
Upvotes: 4
Views: 8134
Reputation: 51000
You do not have to have a main function in Python and writing separate files without a main function, to be imported into other programs, is the normal and correct way of doing Python programming.
When a Python file is loaded (either using import
or by getting executed from the command line) each statement in the program is executed at that time. Statements that are def
or class
statements create a function or class definition for later use. Statements that are are not inside a def
or class
will be executed right away.
Therefore, the equivalent of a main()
function in other languages is actually the set of executable statements found in your file. If you limit these to def
and/or class
statements, you will get the effect you want.
Upvotes: 6