0

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.

d.b
  • 32,245
  • 6
  • 36
  • 77
  • 1
    `__file__` refers to the file containing the code that references that name. If you want the name of the file that instantiated an object, you'd need to pass `__file__` as a parameter to the instantiation. – jasonharper Aug 16 '22 at 19:31
  • @jasonharper, that's what I ended up doing. I need to pass `__file__` from all places where I import `Foo`. Is there no way to avoid that? – d.b Aug 16 '22 at 19:33
  • 1
    You can also use the `inspect` module like here: https://docs.python.org/3/library/inspect.html#inspect.stack – Dr. V Aug 16 '22 at 20:06

0 Answers0