Skip to content Skip to sidebar Skip to footer

How To Find The Name Of A Property From A Python Class

I'm trying to get a property to print the name that it's assigned to in the owner class in python, and I've worked out a method that seems to work if and only if the property is di

Solution 1:

You could traverse the base classes using the __mro__ attribute of the class, looking for the property in each class' __dict__:

classAuto(object):def__get__(self, instance, owner):
        attr_name = (k 
            for klass in owner.__mro__
            for (k, v) in klass.__dict__.iteritems() 
            if v == self).next()
        return attr_name

"mro" stands for method resolution order, and is a list of the base classes in the order that python will look for methods and other class-defined attributes. Scanning this list means you'll look up the property across the base classes in the same order Python would use.

Your example code works correctly with the above code:

>>>h = Handler()>>>print h.CLIENT_ID
CLIENT_ID
>>>s = SubHandler()>>>print s.CLIENT_ID
CLIENT_ID

Post a Comment for "How To Find The Name Of A Property From A Python Class"