views:

644

answers:

4

Hello, could i get:

  • 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

Thanks.

+3  A: 
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: http://mail.python.org/pipermail/python-list/2001-August/100181.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

SpliFF
+6  A: 

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()
Andrew Hare
Are you trying to run it from the command line? It obviously isn't defined then; try creating a file with the code and doing python filename - it will work as expected.
Paolo Bergantino
run it from file
mtasic
Why not inspect.currentframe ?
ΤΖΩΤΖΙΟΥ
+3  A: 
import sys

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

a = A()
mtasic
+1  A: 

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.

Daniel Roseman