Skip to content

Instantly share code, notes, and snippets.

@Sorseg
Last active December 16, 2015 09:38
Show Gist options
  • Save Sorseg/5413889 to your computer and use it in GitHub Desktop.
Save Sorseg/5413889 to your computer and use it in GitHub Desktop.
class AssignOnce:
''' Descriptor, which prevents accidential overwriting of attributes:
>>> class T:
... a = AssignOnce('a')
...
>>> t = T()
>>> t.a
>>> t.a = 3
>>> t.a = 4
Traceback (most recent call last):
...
ValueError: Overwriting a
>>> t.a = None
>>> t.a = 10
'''
def __init__(self, name):
self.name = '_'+name
def __get__(self, obj, owner=None):
return getattr(obj, self.name, None)
def __set__(self, obj, val):
if val != None and getattr(obj, self.name, None) != None:
raise ValueError("Overwriting "+self.name[1:])
setattr(obj, self.name, val)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment