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_prefix
property. Default_
.name (str, optional) – sets the field_prefix property. Default is the name of
originator
object.cancel_error (bool, optional) – sets the cancel_error property. Default
True
.rule_error (bool, optional) – sets the
rule_error
property. DefaultTrue
.assign_true_not_required (bool, optional) – sets the
assign_true_not_required
property. DefaultTrue
.type_instance_check (bool, optional) – If
True
andKwargsHelper.assign`()
argtypes
is set then values will be tested also for isinstance rather then just type check if type check isFalse
. IfFalse
then 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
obj
passed 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_kwargs
passed into to constructor.field (str, optional) –
the name of the field to assign a value. If
field
is omitted then field name is built usinginstance.field_prefix
+key
. If included theninstance.field_prefix
will be ignored. Defaults toNone
.See also: Assign Field Value
require (bool, optional) –
Determins if
key
is required to be inobj_kwargs
passed into to constructor. ifdefault
is passed in thenrequire
is 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_kwargs
passed into to constructor. Ifdefault
is passed in thenrequire
is ignored. Defaults toNO_THING
which 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
str
thentypes=[str]
. If value is required to bestr
orint
thentypes=[str, int]
. In this example if value is not typestr
thenTypeError
is raised. Iftypes
is omitted then a value can be any type unless there is a rule inrules
that 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
types
is included thentypes
takes priority over this arg. All rules must validate asTrue
before 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
types
is included thentypes
takes priority over this arg. Any rule that validates asTrue
results in assignment taking place. Defaults toNone
.See also: Assign Rule Checking
- Returns
True
if attribute assignment is successful; Otherwise,False
- Return type
bool
- Raises
RuleError – If
rule_error
isTrue
and Validation ofrules_all
orrules_any
fails.TypeError – If validation of
types
fails.
- assign_helper(helper: kwhelp.HelperArgs) bool [source]
Assigns attribute value using instance of HelperArgs. See
assign()
method.- Parameters
helper (HelperArgs) – instance to assign.
- Returns
True
if 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_kwargs
passed into constructor tooriginator
, unless the event is canceled inBeforeAssignAutoEventArgs
then 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
str
thentypes=[str]
. If all values are required to bestr
orint
thentypes=[str, int]
.If
types
is omitted then values can be any type unless there is a rule inrules
that 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
types
is included thentypes
takes priority over this arg. All rules must validate asTrue
before 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
types
is included thentypes
takes priority over this arg. Any rule that validates asTrue
results in assignment taking place. Defaults toNone
.See also: Assign Rule Checking
- Returns
True
of all key, value pairs are added; Otherwise,False
.- Return type
bool
- Raises
RuleError – If
rule_error
isTrue
and Validation of rules fails.TypeError – If validation of
types
fails.
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_kwargs
arg.- Parameters
key (str) – Key value to check for existance.
- Returns
True
ifkey
exist; Otherwise,False
.- Return type
bool
- property assign_true_not_required: bool
Determines
assign_true_not_required
Option. IfTrue
then and a non-required arg is assigned viaassign()
. thenassign()
returnsTrue
even if the arg failed to be applied. In anafter callback
method set byadd_handler_after_assign()
success inAfterAssignEventArgs.success
property isFalse
if 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
BeforeAssignEventArgs
of 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 whenfield
is 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_kwargs
arg
- property name: str
Determins name option.
name
that represents theoriginator
in 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
True
rule testing will occur before assign value to attribute. IfTrue
andrule_error
isTrue
then rule errors will prevent assigning value. IfFalse
then 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_kwargs
This would be a set of keys that were never used passed into the constructor.