0

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?

1
  • 2
    __file__ works anywhere within module, be that inside a class or outside. Commented Aug 17, 2012 at 7:17

1 Answer 1

3

__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
Sign up to request clarification or add additional context in comments.

1 Comment

Note that if you specifically want to get the .py file, as opposed to the .pyc, you'll need to add an if statement to check self.myLoc for that and adjust.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.