Python: Use dictionary as argument to create class or model instance

Sometimes you have to dynamically generate the initial arguments for an object but not sure which ones to pass.

Instead of initialising each arg as "None" and setting them all, just pass it a dict instead. That way, anything not specified is assumed to be default value.

data = {
'group': group,
'property': property,
'node': product.node.get(),
'rendered_data': None,
'data': None,
'sort_text': None,
'sort_number_asc': None,
'sort_number_desc': None,
}

# Do whatever logic you need here
if value:
data['rendered_data'] = value
data['data'] = int(value)

# The ** allows data dict to be used as keyword args.
property = Property(**data)
property.save()

Now you can instantiate LIKE A (Tommy Lee Jones) BOSS!

wtf-photos-videos-mr-super-jones

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog