Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 532
drewrobb Avatar asked Jul 15 '11 17:07

drewrobb


2 Answers

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)

like image 75
viraptor Avatar answered Sep 24 '22 08:09

viraptor


AFAIK, the class object is not available until the class definition has been "executed", so it's not possible to get it during class definition.

If you need the class name for later use but don't use it during class definition (e.g. to compute other field names, or some such thing), then you can still automate the process using a class decorator.

def classname ( field ):
    def decorator ( klass ):
        setattr(klass, field, klass.__name__)
        return klass
    return decorator

(Caveat: not tested.)

With this definition, you can get something like:

@classname(field='x')
class Foo:
    pass

and you would get field x with the class name in it, as in:

print Foo.x
like image 24
André Caron Avatar answered Sep 24 '22 08:09

André Caron