Should I have a main function in my Python code?
Is it possible to write python code with a bunch of functions, but without the main function. The purpose of this script is to allow other scripts to import some of the functions. I'll call it setvar_general.py or whatever will be imported by a series of other setvar_x scripts. While these setvar_x do more specific things, setvar_general does nothing more than provide building blocks. Therefore, there is no need to define the main function in setvar_general.py.
I guess it all comes down to the question "should I have a main function"?
source to share
You don't need to have a main function in Python and write separate files without a main function that need to be imported into other programs, this is the normal and correct way to program Python.
When a Python file is loaded (either using import
or executing from the command line), every statement in the program is executed at that time. Operators def
either class
create a function or class definition for later use. Statements that are not inside def
or class
will be executed immediately.
Hence, the equivalent of a function main()
in other languages ββis actually a set of executable statements found in your file. If you restrict them to operators def
and / or class
, you get the desired effect.
source to share