Reputation: 140427
I want to implement certain functionality using python that can be used in two ways:
python mylib.py
My first attempts look like this.
mylib.py:
from __future__ import print_function
import sys
class A(object):
def __init__(self, args):
print("my args: {}".format(args))
def main():
a = A(sys.argv)
print("got {}".format(a))
main()
Which I can directly invoke, or use elsewhere, like usage.py:
import mylib
mylib.A("bla")
That works, but it seems the import causes main()
to be executed as well:
python scripts/using.py blub
my args: ['scripts/using.py', 'blub']
got <mylib.A object at 0x7ff17bc736d0>
my args: bla
Questions:
main()
from running when I go for python using.pl
?And beyond that:
Upvotes: 1
Views: 32
Reputation: 16733
Since @CoryKramer has already answered the first part of the question, let me take a shot at the second part.
Code should exists where it belongs. If it has anything to do with parsing the script or the main execution, then it should be in the script. Any other piece of code shouldn't be the part of script file.
Generally, in production code, you should never import from a script file. The common code should exist in it's own class in a separate file or just in a separate file in case of procedural approach. This way the code in your script would be succinct and the code in the common file is reusable in other production code and you won't run a risk of accidentally executing a script, just to use the common code.
# common.py
class A(object):
def __init__(self, args):
print("my args: {}".format(args))
# mylib.py
from common import A
if __name__ == '__main__':
a = A(sys.argv)
print("got {}".format(a))
Upvotes: 0
Reputation: 117866
This is why you add
if __name__ == '__main__':
main()
If this .py file is directly invoked, your main
will run. If your file is simply imported, it will not run main
. See here
Upvotes: 2