Chris
Chris

Reputation: 31286

Can one find the originating file from a class instance in python3?

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

Upvotes: 1

Views: 70

Answers (2)

Carl_M
Carl_M

Reputation: 948

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

Upvotes: 1

Alex Waygood
Alex Waygood

Reputation: 7579

inspect.getfile will do it for you.

Upvotes: 3

Related Questions