Python | Getting Filename of File Which is Using Specified Class

Question:

I wrote a class on a file called a.py and am running a program on main.py that uses the class from a.py. I’m trying to get the filename of the file that’s running the class on a.py from a.py so that running the class from a.py returns main.py since that’s the file that’s using the class.

If this is confusing I can explain more.

class a:
  def __init__(self):
    print(filename of file thats using this class)
Asked By: Walker

||

Answers:

You could do something like this:

class foo():
    def __init__(self) -> None:
        self.where_am_i = None

# assume this is in a separate file
f = foo()
# get name of current file -- this is a Python feature
f.where_am_i = __file__
print(f.where_am_i)

Output:

<insert file where f was initialized here>
Answered By: Ryan

Fixed using sys.argv[0] to find the running file.

Answered By: Walker
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.