Reputation: 44275
Although there are some related threads according to find the source file of a python module, I did not find an answer on how to get the filename from within a python class in a most simple and reliable way. For a hypothetical file located at /usr/local/TestLib.py
:
class MyTest(object):
def __init__(self):
myLocation = XXX
I want the variable myLocation
to contain the string /usr/local/TestLib.py
. __file__
does not seem to work inside my class.
How should I do that?
Upvotes: 0
Views: 855
Reputation: 10116
__file__
should work in a class like that. Perhaps you thought it didn't work because it doesn't necessarily return the full path. __file__
is a litte funky in terms of how it handles the path, so if you want the full path, you may have to tack on the first part of the path as in this example. (For details on this, check out this question: Python __file__ attribute absolute or relative? .)
import os
class Foo:
def __init__(self):
self.myLoc = os.path.abspath(__file__)
f = Foo()
print f.myLoc
Upvotes: 3