construct_dict¶
-
privex.helpers.common.
construct_dict
(cls: Union[Type[T], C], kwargs: dict, args: Iterable = None, check_parents=True) → Union[T, Any][source]¶ Removes keys from the passed dict
data
which don’t exist oncls
(thus would get rejected as kwargs) usingget_function_params()
. Then create and return an instance ofcls
, passing the filteredkwargs
dictionary as keyword args.Ensures that any keys in your dictionary which don’t exist on
cls
are automatically filtered out, instead of causing an error due to unexpected keyword arguments.Example - User class which only takes specific arguments
First let’s define a class which only takes three arguments in it’s constructor - username, first_name, last_name.
>>> class User: ... def __init__(self, username, first_name=None, last_name=None): ... self.username = username ... self.first_name, self.last_name = first_name, last_name ...
Now we’ll create a dictionary which has those three arguments, but also the excess
address
andphone
.>>> data = dict(username='johndoe123', first_name='John', last_name='Doe', ... address='123 Example St', phone='+1-123-000-1234')
If we tried to directly pass data as keyword args, we’d get an error:
>>> john = User(**data) TypeError: __init__() got an unexpected keyword argument 'address'
But by using
construct_dict()
, we’re able to construct aUser
, as this helper function detects that the excessaddress
andphone
are not valid parameters forUser
’s constructor.>>> from privex.helpers import construct_dict >>> john = construct_dict(User, data) >>> print(john.username, john.first_name, john.last_name) johndoe123 John Doe
Example - A function/method which only takes specific arguments
Not only can
construct_dict()
be used for classes, but it can also be used for any function/method.Here’s an example using a simple “factory function” which creates user objects:
>>> def create_user(username, first_name=None, last_name=None): ... return User(username, first_name, last_name) >>> >>> data = dict( ... username='johndoe123', first_name='John', last_name='Doe', ... address='123 Example St', phone='+1-123-000-1234' ... ) >>> # We can't just pass data as kwargs due to the extra keys. >>> create_user(**data) TypeError: create_user() got an unexpected keyword argument 'address' >>> # But we can call the function using construct_dict, which filters out the excess dict keys :) >>> john = construct_dict(create_user, data) >>> print(john.username, john.first_name, john.last_name) johndoe123 John Doe
- Parameters
cls (Type[T]|callable) – A class (not an instance) or callable (function / lambda) to extract and filter the parameter’s from, then call using filtered
kwargs
andargs
.kwargs (dict) – A dictionary containing keyword arguments to filter and use to call / construct
cls
.args (list|set) – A list of positional arguments (NOT FILTERED!) to pass when calling/constructing
cls
.check_parents (bool) – (Default:
True
) Ifobj
is a class and this is True, will recursively grab the constructor parameters for all parent classes ofcls
and merge them into the returned dict.
- Return Any func_result
If
cls
was a function/method, the return result will be the returned data/object from the function passed.- Return T cls_instance
If
cls
was a class, then the return result will be an instance of the class.