How do I get the current file, current class, and current method with Python?

Question:

  • Name of the file from where code is running
  • Name of the class from where code is running
  • Name of the method (attribute of the class) where code is running
Asked By: Max Frai

||

Answers:

self.__class__.__name__  # name of class i'm in

for the rest the sys and trace modules

http://docs.python.org/library/sys.html
http://docs.python.org/library/trace.html

Some more info:
https://mail.python.org/pipermail/python-list/2001-August/096499.html
and
http://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_code.html

did you want it for error reporting because the traceback module can handle that:

http://docs.python.org/library/traceback.html

Answered By: SpliFF

Here is an example of each:

from inspect import stack

class Foo:
    def __init__(self):
        print __file__
        print self.__class__.__name__
        print stack()[0][3]

f = Foo()
Answered By: Andrew Hare
import sys

class A:
    def __init__(self):
        print __file__
        print self.__class__.__name__
        print sys._getframe().f_code.co_name

a = A()
Answered By: mtasic85

Be very careful. Consider:

class A:
    pass

B = A
b = B()

What is the ‘class name’ of b here? Is it A, or B? Why?

The point is, you shouldn’t need to know or care. An object is what it is: its name is very rarely useful.

Answered By: Daniel Roseman
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.