Created
September 12, 2014 00:37
-
-
Save eevee/a7ba51b21b34b5fdd266 to your computer and use it in GitHub Desktop.
frozenobject
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
class FrozenMeta(type): | |
"""Metaclass for freezing a type after construction. Only ``__init__`` | |
will be allowed to assign to attributes. | |
""" | |
def __call__(cls, *args, **kwargs): | |
obj = super(FrozenMeta, cls).__call__(*args, **kwargs) | |
obj.__frozen__ = True | |
return obj | |
class frozenobject(object, metaclass=FrozenMeta): | |
__slots__ = ('__frozen__',) | |
def __setattr__(self, attr, value): | |
if getattr(self, '__frozen__', False): | |
raise FrozenError("This object is frozen and cannot be modified.") | |
super(frozenobject, self).__setattr__(attr, value) | |
def __delattr__(self, attr): | |
if getattr(self, '__frozen__', False): | |
raise FrozenError("This object is frozen and cannot be modified.") | |
super(frozenobject, self).__delattr__(attr) | |
class FrozenError(TypeError): | |
pass | |
class MediaItem(frozenobject): | |
def __init__(self, type, id, url, caption): | |
self.type = type | |
self.id = id | |
self.url = url | |
self.caption = caption | |
@property | |
def is_video(self): | |
return self.type == 'video' | |
class MediaItem2(frozenobject): | |
__slots__ = ('type', 'id', 'url', 'caption') | |
def __init__(self, type, id, url, caption): | |
self.type = type | |
self.id = id | |
self.url = url | |
self.caption = caption | |
@property | |
def is_video(self): | |
return self.type == 'video' | |
import pytest | |
item = MediaItem('video', 3, 'http://.../', 'this is my video') | |
print(item.is_video) | |
with pytest.raises(FrozenError): | |
item.adhoc = 'lololol' | |
with pytest.raises(FrozenError): | |
item.type = 'photo' | |
item = MediaItem2('video', 3, 'http://.../', 'this is my video') | |
print(item.is_video) | |
with pytest.raises(FrozenError): | |
item.adhoc = 'lololol' | |
with pytest.raises(FrozenError): | |
item.type = 'photo' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment