Raising an exception on updating a 'constant' attribute in python

前端 未结 5 1436
逝去的感伤
逝去的感伤 2021-01-14 15:29

As python does not have concept of constants, would it be possible to raise an exception if an \'constant\' attribute is updated? How?

class MyClass():
            


        
5条回答
  •  借酒劲吻你
    2021-01-14 16:05

    You can use a metaclass to achieve this:

    class ImmutableConstants(type):
        def __init__(cls, name, bases, dct):
            type.__init__(cls, name, bases, dct)
    
            old_setattr = cls.__setattr__
            def __setattr__(self, key, value):
                cls.assert_attribute_mutable(key)
                old_setattr(self, key, value)
            cls.__setattr__ = __setattr__
    
        def __setattr__(self, key, value):
            self.assert_attribute_mutable(key)
            type.__setattr__(self, key, value)
    
        def assert_attribute_mutable(self, name):
            if name.isupper():
                raise AttributeError('Attribute %s is constant' % name)
    
    class Foo(object):
        __metaclass__ = ImmutableConstants
        CONST = 5
        class_var = 'foobar'
    
    Foo.class_var = 'new value'
    Foo.CONST = 42 # raises
    

    But are you sure this is a real issue? Are you really accidentally setting constants all over the place? You can find most of these pretty easily with a grep -r '\.[A-Z][A-Z0-9_]*\s*=' src/.

提交回复
热议问题