Here is the project folder structure:
foo/
├─ foo/
│ ├─ foo.py
│ ├─ __init__.py
__main__.py
# foo.py
import os
class Foo:
def __init__(self):
self.origin = os.path.realpath(__file__)
# __init__.py
from .foo import Foo
# __main__.py
from .foo import Foo
import os
if __name__ == "__main__":
my_foo = Foo()
print("\twant:", os.path.realpath(__file__))
print("\thave:", my_foo.origin)
When I run python -m foo
from outside the root, I get:
want: ...\foo\__main__.py
have: ...\foo\foo\foo.py
Since Foo()
is being instantiated inside __main__.py
I assumed, __file__
would point to the path of __main__.py
. That does not seem to be the case. What do I need to do to make sure the second line (have
) is the same as the first line?
Maybe my problem is in the same vein as Why is Python running my module when I import it, and how do I stop it?, but those answers did not work for me.