Created
May 15, 2018 16:27
-
-
Save Quidge/c81865985801a3655b9053627e1d754d to your computer and use it in GitHub Desktop.
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 ErrorOnDuplicateSet(object): | |
""" | |
This class behaves just like a set type collection, but will error if | |
a duplicate is added to the collection. | |
""" | |
__emulates__ = set | |
def __init__(self): | |
self.data = set() | |
@sa.orm.collections.collection.appender | |
def append(self, item): | |
try: | |
assert item not in self.data | |
except: | |
raise | |
else: | |
self.data.add(item) | |
def remove(self, item): | |
self.data.remove(item) | |
def __iter__(self): | |
return iter(self.data) | |
def __repr__(self): | |
return str(self.data) | |
# The allows the following behavior (which I belive is what I should want): | |
>>> from app.models import User | |
>>> u = User(email='append_test@email.com', password='password') | |
>>> u.sz_shirt_dress_sleeve | |
set() | |
>>> from app.models import SizeKeyShirtDressSleeve | |
>>> size_obj = SizeKeyShirtDressSleeve.query.filter(SizeKeyShirtDressSleeve.size == 3000).first() | |
>>> u.sz_shirt_dress_sleeve.append(size_obj) | |
>>> u.sz_shirt_dress_sleeve | |
{Dress shirt sleeve size: 3000} | |
>>> | |
# And errors appropriately (I think? I don't have a best practice for generating custom errors.) | |
>>> u.sz_shirt_dress_sleeve.append(size_obj) | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
File "/Users/lirum/Envs/ltf-nZ8b7LIQ/lib/python3.6/site-packages/sqlalchemy/orm/collections.py", line 995, in wrapper | |
return method(*args, **kw) | |
File "/Users/lirum/Documents/programming/projects/ltf/app/models.py", line 20, in append | |
assert item not in self.data | |
AssertionError | |
>>> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment