How to add attribute to python *class* that is _not_ inherited?

270 views Asked by At

I need to be able to set a flag on a class (not on an instance of a class) which is not visible to a subclass. The question is, is it possible, and how would I do it if it is?

To illustrate, I want something like this:

class Master(SomeOtherClass):
    __flag__ = True

class Child(Master):
    pass

... where hasattr(Master, "__flag__") should return True for Master but False for Child. Is this possible? If so, how? I don't want to have to explicitly set __flag__ to false in every child.

My initial thought was to define __metaclass__, but I don't have the luxury of doing that because Master inherits from some other classes and metaclasses I don't control and which are private.

Ultimately I'm wanting to write a decorator so that I can do something like:

@hide_this
class Master(SomeOtherClass): pass

@hide_this
class Child(Master): pass

class GrandChild(Child): pass
...
for cls in (Master, Child, GrandChild)
    if cls.__hidden__:
        # Master, Child
    else:
        # GrandChild
1

There are 1 answers

2
jonrsharpe On BEST ANSWER

You were very close:

class Master(SomeOtherClass):
    __flag = True

class Child(Master):
    pass

Two leading underscores without trailing underscores invokes name mangling, so the attribute will be named _Master__flag. Therefore if you check:

hasattr(cls, '_{}__flag'.format(cls.__name__))

it will only be True for Master, not Child.