I have written a package with the 'standard' minimal structure. It looks like this:
my_package/
my_package/
__init__.py
setup.py
__init__.py
contains a class and as such can simply be imported and used as one would expect.
However, the code really lends itself to be used in a command-line-way, e.g.
python my_package --arg1 "I like bananas."
At first, I just had an if __name__ == '__main__'
check in __init__
which would then use argparse
. This works but it isn't pretty, because it would mean that you'd call it from the command line like so:
python my_package/__init__.py --arg1 "I like bananas."
From what I read, this is where a __main__.py
file comes in which would be executed as the default script inside a folder (similar to a index.html
file on a website). The idea I have is to then simply import __init__.py
, run argparse and feed the arguments to the class constructor. Like so:
import argparse
from __init__ import MyClass
parser = argparse.ArgumentParser()
parser.add_argument("--arg1", help="Some dummy value")
args = parser.parse_args()
my_class = MyClass(**vars(args))
my_class.do_stuff()
Is this how similar packages ought to be structured, or is there a better way?
The above works but PyCharm tells me that in __main__.py
__init__
is an unresolved reference. Same for MyClass
on that import line. When I use .__init__
instead (with a dot) the warning goes away but then the code doesn't work anymore, giving me a ImportError: attempted relative import with no known parent package
.