mongodb - Python Design Pattern for data transformations -
i find myself doing quite bit:
if 'id' in kwargs: query['_id'] = objectid(kwargs.pop('id')) if 'name' in kwargs: query['event'] = kwargs.pop('name') if 'keywords' in kwargs: keywords = kwargs.pop('keywords') query['keywords'] = { '$in': keywords }
ignore implementation specifics. essential point here i'm dealing 2 data structures share similar data , performing both simple, repetitive , more complex transformations.
are there design patterns or other developer-friendly ways of making these types of transformations easier code?
i thought creating table , associated function transform simple attribute names have feeling won't play when dealing more complicated data transformations. also, method may not save me whole lot of work in long run.
any suggestions?
you @ least clean out if
s map. when have large group of transforms.
transforms = {'id' : ('_id', lambda val: objectid(val)), 'name' : ('event', lambda val: val), 'keywords' : ('keywords', lambda val: val)} kwargs_key in kwargs.keys(): try: query_key, transform = transforms[kwargs_key] except keyerror: # default or error handling else: query[query_key] = transform(kwargs.pop(kwargs_key))
if wrap in class , make transforms
class or instance attribute, can add or overwrite transforms @ runtime if want.
Comments
Post a Comment