Last active
September 10, 2018 20:47
-
-
Save wheaties/5c002e089321ec6427cd2e86251213e8 to your computer and use it in GitHub Desktop.
Python write once field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from weakref import WeakKeyDictionary | |
from collections.abc import Hashable | |
#Only works with hashable objects | |
class WriteOnce: | |
def __init__(self): | |
self.__values = WeakKeyDictionary() | |
def __get__(self, obj, obj_type=None): | |
if obj_type is not None: | |
return self | |
return self.__values.get(obj) if isinstance(obj, Hashable) else AttributeError | |
def __set__(self, obj, value): | |
if isinstance(obj, Hashable) and not obj in self.__values : | |
self.__values[obj] = value | |
else: | |
return AttributeError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment