pythonmetaprogrammingpython-2.x

Python name of class in class body


Is it possible to get the class name within the body of a class definition?

For example,

class Foo():
    x = magic() # x should now be 'Foo'

I know that I can do this statically outside of the class body using a class method:

class Bar():
    @classmethod
    def magic(cls):
        print cls.__name__

Bar.magic()

However this isn't what I want, I want the class name in the class body


Solution

  • Ok - got one more solution - this one is actually not that complex!

    import traceback
    
    def magic():
       return traceback.extract_stack()[-2][2]
    
    class Something(object):
       print magic()
    

    It will print out "Something". I'm not sure if extracted stack format is standardised in any way, but it works for python 2.6 (and 2.7 and 3.1)