KwargsHelper Class
- class kwhelp.KwargsHelper(originator: object, obj_kwargs: dict, **kwargs)[source]
kwargs helper class. Assigns attributes to class with various checks
Example
class MyClass: def __init__(self, **kwargs): self._msg = '' kw = KwargsHelper(self, {**kwargs}) kw.assign(key='msg', require=True, types=['str']) kw.assign(key='length', types=['int'], default=-1) @property def msg(self) -> str: return self._msg @property def length(self) -> str: return self._length
>>> my_class = MyClass(msg='Hello World') >>> print(my_class.msg) Hello World >>> print(my_class.length) -1
- __init__(originator: object, obj_kwargs: dict, **kwargs)[source]
Constructor
- Parameters
originator (object) – object that attributes are assigned to via
assign()method. This is usually a class.obj_kwargs (dict) – The dictionary of key value args used to set values of attributes. Often passed in as
obj_kwargs = {**kwargs}
- Keyword Arguments
field_prefix (str, optional) – sets the
field_prefixproperty. Default_.name (str, optional) – sets the field_prefix property. Default is the name of
originatorobject.cancel_error (bool, optional) – sets the cancel_error property. Default
True.rule_error (bool, optional) – sets the
rule_errorproperty. DefaultTrue.assign_true_not_required (bool, optional) – sets the
assign_true_not_requiredproperty. DefaultTrue.type_instance_check (bool, optional) – If
TrueandKwargsHelper.assign`()argtypesis set then values will be tested also for isinstance rather then just type check if type check isFalse. IfFalsethen values willl only be tested as type. DefaultTrue
- Raises
TypeError – if any arg is not of the correct type.
- add_handler_after_assign(callback: Callable[[kwhelp.KwargsHelper, kwhelp.AfterAssignEventArgs], None])[source]
Add handler afer assign
- Parameters
callback (Callable[['KwargsHelper', AfterAssignEventArgs], None]) – Callback Method
See also
- add_handler_after_assign_auto(callback: Callable[[kwhelp.KwargsHelper, kwhelp.AfterAssignAutoEventArgs], None])[source]
Adds handler for after assign auto
- Parameters
callback (Callable[['KwargsHelper', AfterAssignAutoEventArgs], None]) – Callback Method
See also
- add_handler_before_assign(callback: Callable[[kwhelp.KwargsHelper, kwhelp.BeforeAssignEventArgs], None])[source]
Add handler before assign
- Parameters
callback (Callable[['KwargsHelper', BeforeAssignEventArgs], None]) – Callback Method
See also
- add_handler_before_assign_auto(callback: Callable[[kwhelp.KwargsHelper, kwhelp.BeforeAssignAutoEventArgs], None])[source]
Adds handler for before assigne auto
- Parameters
callback (Callable[['KwargsHelper', BeforeAssignAutoEventArgs], None]) – Callback Method
See also
- assign(key: str, field: Optional[str] = None, require: bool = False, default: Optional[object] = <kwhelp.helper.NoThing object>, types: Optional[Iterable[type]] = None, rules_all: Optional[Iterable[Callable[[kwhelp.rules.IRule], bool]]] = None, rules_any: Optional[Iterable[Callable[[kwhelp.rules.IRule], bool]]] = None) bool[source]
Assigns attribute value to
objpassed in to constructor. Attributes are created if they do not exist.- Parameters
key (str) – the key of the key, value pair that is required or optional in
obj_kwargspassed into to constructor.field (str, optional) –
the name of the field to assign a value. If
fieldis omitted then field name is built usinginstance.field_prefix+key. If included theninstance.field_prefixwill be ignored. Defaults toNone.See also: Assign Field Value
require (bool, optional) –
Determins if
keyis required to be inobj_kwargspassed into to constructor. ifdefaultis passed in thenrequireis ignored. Defaults toFalse.See also: Assign Require Arg
default (object, optional) –
default value to assign to key attribute if no value is found in
obj_kwargspassed into to constructor. Ifdefaultis passed in thenrequireis ignored. Defaults toNO_THINGwhich will result in default being ignored.See also: Assign Default Value
types (Iterable[type], optional) –
a type list of one or more types that the value of the key value pair must match. For example if a value is required to be only
strthentypes=[str]. If value is required to bestrorintthentypes=[str, int]. In this example if value is not typestrthenTypeErroris raised. Iftypesis omitted then a value can be any type unless there is a rule inrulesthat is otherwise. Defaults toNone.See also: Assign Type Checking
rules_all (Iterable[Callable[[IRule], bool]], optional) –
List of rules that must be passed before assignment can take place. If
typesis included thentypestakes priority over this arg. All rules must validate asTruebefore assignment takes place. Defaults toNone.See also: Assign Rule Checking
rules_any (Iterable[Callable[[IRule], bool]], optional) –
List of rules that must be passed before assignment can take place. If
typesis included thentypestakes priority over this arg. Any rule that validates asTrueresults in assignment taking place. Defaults toNone.See also: Assign Rule Checking
- Returns
Trueif attribute assignment is successful; Otherwise,False- Return type
bool
- Raises
RuleError – If
rule_errorisTrueand Validation ofrules_allorrules_anyfails.TypeError – If validation of
typesfails.
- assign_helper(helper: kwhelp.HelperArgs) bool[source]
Assigns attribute value using instance of HelperArgs. See
assign()method.- Parameters
helper (HelperArgs) – instance to assign.
- Returns
Trueif attribute assignment is successful; Otherwise,False.- Return type
bool
- auto_assign(types: Optional[Iterable[type]] = None, rules_all: Optional[Iterable[Callable[[kwhelp.rules.IRule], bool]]] = None, rules_any: Optional[Iterable[Callable[[kwhelp.rules.IRule], bool]]] = None) bool[source]
Assigns all of the key, value pairs of
obj_kwargspassed into constructor tooriginator, unless the event is canceled inBeforeAssignAutoEventArgsthen key, value pair will be added automacally tooriginator.- Parameters
types (Iterable[type], optional) –
a type list of one or more types that the value of the key value pair must match. For example if all values are required to be only
strthentypes=[str]. If all values are required to bestrorintthentypes=[str, int].If
typesis omitted then values can be any type unless there is a rule inrulesthat is otherwise. Defaults toNone.See also: Assign Type Checking
rules_all (Iterable[Callable[[IRule], bool]], optional) –
List of rules that must be passed before assignment can take place. If
typesis included thentypestakes priority over this arg. All rules must validate asTruebefore assignment takes place. Defaults toNone.See also: Assign Rule Checking
rules_any (Iterable[Callable[[IRule], bool]], optional) –
List of rules that must be passed before assignment can take place. If
typesis included thentypestakes priority over this arg. Any rule that validates asTrueresults in assignment taking place. Defaults toNone.See also: Assign Rule Checking
- Returns
Trueof all key, value pairs are added; Otherwise,False.- Return type
bool
- Raises
RuleError – If
rule_errorisTrueand Validation of rules fails.TypeError – If validation of
typesfails.
Note
Call back events are supported via
add_handler_before_assign_auto()andadd_handler_after_assign_auto()methods.
- is_key_existing(key: str) bool[source]
Gets if the key exist in kwargs dictionary passed in to the constructor by
obj_kwargsarg.- Parameters
key (str) – Key value to check for existance.
- Returns
Trueifkeyexist; Otherwise,False.- Return type
bool
- property assign_true_not_required: bool
Determines
assign_true_not_requiredOption. IfTruethen and a non-required arg is assigned viaassign(). thenassign()returnsTrueeven if the arg failed to be applied. In anafter callbackmethod set byadd_handler_after_assign()success inAfterAssignEventArgs.successproperty isFalseif arg was not assigned. DefaultTrue- Getter
Gets option value.
- Setter
Sets option value.
- property cancel_error: bool
Determins if an error will be raised if cancel is set in
BeforeAssignEventArgsof a callback. DefaultTrue.- Getter
Gets cancel_error option.
- Setter
Sets cancel_error option.
- property field_prefix: str
Determines the field prefix option. The prefix use when setting attributes: Default:
_. To add args without a prefix set the valuefield_prefix = ''This parameter is ignored whenfieldis used inassign()method such as:assign(msg='hi', field='message')- Getter
Gets the field prefix option.
- Setter
Sets the field prefix option.
- property kw_args: Dict[str, Any]
Gets the kwargs dictionary passed in to the constructor by
obj_kwargsarg
- property name: str
Determins name option.
namethat represents theoriginatorin error messages. Default:type(originator)__name__- Getter
Gets name option.
- Setter
Sets name option
- property originator: object
Gets originator option
object that attributes are assigned to via
assign()method. This is usually a class.
- property rule_error: bool
Determins rule_error option. Default
True- Getter
Gets rule_error option.
- Setter
Sets rule_error option.
- property rule_test_before_assign: bool
Determines rule_test_before_assign option. If
Truerule testing will occur before assign value to attribute. IfTrueandrule_errorisTruethen rule errors will prevent assigning value. IfFalsethen attribute values will be assigned even if rules does not validate. Validation can still fail and errors can still be raised, except now the validation will take place after attribute value has been assigned. Default:True- Getter
Gets rule_test_before_assign option.
- Setter
Sets rule_test_before_assign option.
- property unused_keys: Set[str]
Gets any unused keys passed into constructor via
obj_kwargsThis would be a set of keys that were never used passed into the constructor.