0

I am trying to make a class called DevOpt, that is used as a "static class" (not instantiated), and any static attribute look up on it returns False , however the __getattribute__ is not working (from my research it should override instance and class attribute look ups):

# Python 3.8
class DevOpt:                    
    def __getattribute__(obj, _):
        return False             

# Want DevOpt.anything to return False:
>>> DevOpt.foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'DevOpt' has no attribute 'foo'

>>> DevOpt.__getattribute__(DevOpt, 'foo')
False
run_the_race
  • 1,344
  • 2
  • 36
  • 62
  • 5
    `__getattribute__` is only invoked on _instance_ attribute access - if you want it invoked on _class_ attribute access, it needs to be on the _meta_-class. – jonrsharpe Mar 23 '22 at 20:53
  • [Good reading material on metaclasses](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python). Some of the syntax in that answer is from Python 2, but most of it's still relevant. – Silvio Mayolo Mar 23 '22 at 20:55
  • This seems like a very unusual use case... Could you describe a bit more about _why_ you want this behavior? If you're looking for something that won't be instantiated directly, but which would allow subclasses, maybe look into "abstract base classes" instead? – Sarah Messer Mar 23 '22 at 20:58
  • @SarahMesser The use case is: there are a bunch or properties (flags) set in an object during dev, then if not in DEV (the file where these flags are defined is not imported, and I dont want to duplicate all the flag names is a separate brittle file), so in prod when looking up DevOpt, the flag should always be off (False). The way its used get complicated so checks like DEBUG and DevOpt... doesnt work because sometimes DEBUG is True, and there are no DevOpts, and not keen for lots of hasattr tests. – run_the_race Mar 23 '22 at 21:03

0 Answers0