1

For example,

# foo.py
class Foo:
   foo = "foo"

# main.py
from foo import Foo

f = Foo()

print(f.__file__)  # doesn't work, but is there something that would?

(ideally)$: python3 main.py 
/the/whole/path/to/foo.py

2 Answers 2

3

inspect.getfile will do it for you.

Sign up to request clarification or add additional context in comments.

Comments

1

Use inspect.

Demonstration when a class is not created in the same file and a class in the source file.

with open('foo_file.py','w') as f_out:
    f_out.write("class Foo:\n\tfoo = \"foo\"")
import inspect
from foo_file import Foo

# Create a local class
class InThisFile:
    pass

def main():
    print(inspect.getfile(Foo))
    print(inspect.getfile(InThisFile))
    x = Foo()
    # Path to the file for the instance of x
    print(inspect.getfile(type(x)))

if __name__ == '__main__':
    main()

Test results:

C:\Users\user\AppData\Roaming\JetBrains\PyCharm2021.3\scratches\foo_file.py
C:\Users\user\AppData\Roaming\JetBrains\PyCharm2021.3\scratches\scratch_22.py
C:\Users\user\AppData\Roaming\JetBrains\PyCharm2021.3\scratches\foo_file.py

5 Comments

Ah, I am looking for a way to get this from the object instantiation... And I screwed up the question
@Chris, you can pass the type(instance) to the getfile.
Think if you add .__class__ to the argument it will work
@VPfB lol same time
Modified and tested answer using ` print(inspect.getfile(type(x)))` to reflect the previous comments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.