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. Default True.

  • assign_true_not_required (bool, optional) – sets the assign_true_not_required property. Default True.

  • type_instance_check (bool, optional) – If True and KwargsHelper.assign`() arg types is set then values will be tested also for isinstance rather then just type check if type check is False. If False then values willl only be tested as type. Default True

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

Callback Usage

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

Callback Usage

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

Callback Usage

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

Callback Usage

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 using instance.field_prefix + key. If included then instance.field_prefix will be ignored. Defaults to None.

    See also: Assign Field Value

  • require (bool, optional) –

    Determins if key is required to be in obj_kwargs passed into to constructor. if default is passed in then require is ignored. Defaults to False.

    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. If default is passed in then require is ignored. Defaults to NO_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 then types=[str]. If value is required to be str or int then types=[str, int]. In this example if value is not type str then TypeError is raised. If types is omitted then a value can be any type unless there is a rule in rules that is otherwise. Defaults to None.

    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 then types takes priority over this arg. All rules must validate as True before assignment takes place. Defaults to None.

    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 then types takes priority over this arg. Any rule that validates as True results in assignment taking place. Defaults to None.

    See also: Assign Rule Checking

Returns

True if attribute assignment is successful; Otherwise, False

Return type

bool

Raises
  • RuleError – If rule_error is True and Validation of rules_all or rules_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 to originator, unless the event is canceled in BeforeAssignAutoEventArgs then key, value pair will be added automacally to originator.

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 then types=[str]. If all values are required to be str or int then types=[str, int].

    If types is omitted then values can be any type unless there is a rule in rules that is otherwise. Defaults to None.

    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 then types takes priority over this arg. All rules must validate as True before assignment takes place. Defaults to None.

    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 then types takes priority over this arg. Any rule that validates as True results in assignment taking place. Defaults to None.

    See also: Assign Rule Checking

Returns

True of all key, value pairs are added; Otherwise, False.

Return type

bool

Raises
  • RuleError – If rule_error is True and Validation of rules fails.

  • TypeError – If validation of types fails.

Note

Call back events are supported via add_handler_before_assign_auto() and add_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 if key exist; Otherwise, False.

Return type

bool

property assign_true_not_required: bool

Determines assign_true_not_required Option. If True then and a non-required arg is assigned via assign(). then assign() returns True even if the arg failed to be applied. In an after callback method set by add_handler_after_assign() success in AfterAssignEventArgs.success property is False if arg was not assigned. Default True

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. Default True.

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 value field_prefix = '' This parameter is ignored when field is used in assign() 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 the originator 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. If True and rule_error is True then rule errors will prevent assigning value. If False 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.