Last active
December 16, 2015 09:38
-
-
Save Sorseg/5413889 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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