Reputation: 10281
I'm creating a Python module mymodule.py
and I need to run a function on import. The function should not be run by the user, and is only necessary to initiate the module properly.
Since it's a module, this won't work:
if __name__ == '__main__':
_main()
I want to follow PEPs and I was simply wondering if there an equivalent of C's main() in a Python module?
...or if I should just write the initialisation code inline (not as a function), or call the function inline.
Upvotes: 0
Views: 147
Reputation: 26315
Yeah have like a top level function that is like a main, something like this:
def interact():
# Your code which handles all the rest of the functions
# For example
print('Welcome to this program!')
filename = input('Please enter the data source file: ')
load_data(filename)
......
And then at the bottom of your script do what you were doing:
if __name__ == '__main__':
interact()
if you want to import other files into the program, like mymodule.py
, just do this:
from mymodule import *
Alternatively, you can test functions out like this:
if __name__ == "__main__":
print test_the_function(123, 456)
When mymodule
is imported, the code is run as before, but when we get to the if statement, Python looks to see what name the module has. Since the module is imported, we know it by the name used when importing it, so __name__
is mymodule
. Thus, the print statement is never reached.
The beautiful thing about python is that it doesn't work like Cs main(). You just start typing, and you've written your first program. The simplicity of python is what makes it so beautiful, I wouldn't try and compare it with C, it just won't work.
You can also check this website out, if has some useful information about the python main():
Upvotes: 0
Reputation: 2004
Running a function on import is not equivalent to C's main()
. C's main()
is run when executing the program.
Everything in a Python module which is top-level (i.e. not in a function) is executed when the module is imported. For example, if this is your module content:
def _on_import():
pass # do something
_on_import()
then _on_import()
is executed when importing the module.
When your module looks like this:
def main():
pass # do something
if __name__ == '__main__':
main()
then main()
is executed when running the python module as a script (e.g. if your module is in file foo.py
and you run python foo.py
). This is basically equivalent to C's main()
.
Upvotes: 1
Reputation: 15290
Code that is not indented into a function will be run as the file is loaded (once). That's probably what you want:
def some_function():
pass
def other_function():
pass
init_value = 0 # This code here is run immediately.
buffer = None
Upvotes: 4