Reputation: 31286
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
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