Last active
September 9, 2019 10:37
-
-
Save ecleel/6777424 to your computer and use it in GitHub Desktop.
method to generate python object from array of kwargs
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
def generate_objects(object_type, obj_ary, default = {}, attr_names = {}): | |
"""Generate objects that is given in `obj_ary` of class `object_type`. | |
Parameters | |
---------- | |
object_type : str | |
the class name | |
obj_ary : array | |
object attribute that will populate the object. | |
default : dict | |
default attributes for all generated objects. | |
attr_names : dict | |
change attribute name from obj_ary | |
""" | |
klass = eval(object_type) | |
instances = [] | |
for object_dict in obj_ary: | |
# change key names. | |
for key, newkey in attr_names.iteritems(): | |
object_dict[newkey] = object_dict[key] | |
object_dict.pop(key) | |
# merge object_dict with default | |
kwargs = dict(object_dict.items() + default.items()) | |
instance = klass(**kwargs) | |
instances.append(instance) | |
return instances | |
# Example of class that work with generate_objects(). | |
class Site(object): | |
def __init__(self, **kwargs): | |
for key in kwargs: | |
setattr(self, key, kwargs[key]) | |
if __name__ == '__main__': | |
generate_objects('Site', | |
[{'scheme': 'http', 'host':'ecleel.com', 'port': 80, 'dirs': '/foo.html'}, | |
{'scheme': 'https', 'host':'yahoo.com', 'port': 443, 'dirs': '/test.html'}], | |
default={'need_authentication': False}, | |
attr_names={'dirs':'path'}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment