Skip to content

Instantly share code, notes, and snippets.

@wheaties
Last active September 10, 2018 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wheaties/5c002e089321ec6427cd2e86251213e8 to your computer and use it in GitHub Desktop.
Save wheaties/5c002e089321ec6427cd2e86251213e8 to your computer and use it in GitHub Desktop.
Python write once field
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