`final` keyword equivalent for variables in Python?

后端 未结 11 1947
忘了有多久
忘了有多久 2021-01-30 20:17

I couldn\'t find documentation on an equivalent of Java\'s final in Python, is there such a thing?

I\'m creating a snapshot of an object (used for restorati

11条回答
  •  -上瘾入骨i
    2021-01-30 20:48

    Python indeed does not have a final type, it does have immutable types such as tuples but that is something else.

    Some of the other Answers here make classes full of pseudo final variables and I prefer my class to only have a few Final types, so I suggest using an descriptor to create the final type:

    from typing import TypeVar, Generic, Type
    
    T = TypeVar('T')
    
    class FinalProperty(Generic[T]):
        def __init__(self, value: T):
            self.__value = value
        def __get__(self, instance: Type, owner) -> T:
            return self.__value
        def __set__(self, instance: Type, value: T) -> None:
            raise ValueError("Final types can't be set")
    

    If you use this class like so:

    class SomeJob:
        FAILED = FinalProperty[str]("Failed")
    

    Then you will not be able to set that variable in any instance of that class. Unfortunately as with the WriteOnceReadWhenever answer you can still set the class variable.

    job = SomeJob()
    job.FAILED = "Error, this will trigger the ValueError"
    SomeJob.FAILED = "However this still works and breaks the protection afterwards"
    

提交回复
热议问题