Python check kwargs
| Source File: check_kwargs.py From espnet with Apache License 2.0 | 6 votes |
def check_kwargs(func, kwargs, name=None):
"""check kwargs are valid for func
If kwargs are invalid, raise TypeError as same as python default
:param function func: function to be validated
:param dict kwargs: keyword arguments for func
:param str name: name used in TypeError (default is func name)
"""
try:
params = inspect.signature(func).parameters
except ValueError:
return
if name is None:
name = func.__name__
for k in kwargs.keys():
if k not in params:
raise TypeError(f"{name}() got an unexpected keyword argument '{k}'")
| Source File: utilities_noconf.py From xrayutilities with GNU General Public License v2.0 | 6 votes |
def check_kwargs(kwargs, valid_kwargs, identifier):
"""
Raises an TypeError if kwargs included a key which is not in valid_kwargs.
Parameters
----------
kwargs : dict
keyword arguments dictionary
valid_kwargs : dict
dictionary with valid keyword arguments and their description
identifier : str
string to identifier the caller of this function
"""
desc = ', '.join(["'%s': %s" % (k, d) for k, d in valid_kwargs.items()])
for k in kwargs:
if k not in valid_kwargs:
raise TypeError("%s: unknown keyword argument ('%s') given; "
"allowed are %s" % (identifier, k, desc))
| Source File: CanConnectionFactory.py From python-uds with MIT License | 6 votes |
def checkKwargs(**kwargs):
if 'interface' in kwargs:
CanConnectionFactory.config['can']['interface'] = kwargs['interface']
if 'baudrate' in kwargs:
CanConnectionFactory.config['can']['baudrate'] = kwargs['baudrate']
if 'device' in kwargs:
CanConnectionFactory.config['peak']['device'] = kwargs['device']
if 'appName' in kwargs:
CanConnectionFactory.config['vector']['appName'] = kwargs['appName']
if 'channel' in kwargs:
CanConnectionFactory.config['vector']['channel'] = kwargs['channel']
| Source File: __init__.py From pytest-ansible with MIT License | 5 votes |
def check_required_kwargs(self, **kwargs):
"""Raise a TypeError if any required kwargs are missing."""
for kwarg in self._required_kwargs:
if kwarg not in self.options:
raise TypeError("Missing required keyword argument '%s'" % kwarg)
| Source File: base.py From mlens with MIT License | 5 votes |
def check_kwargs(kwargs, forbidden):
"""Pop unwanted arguments and issue warning"""
for f in forbidden:
s = kwargs.pop(f, None)
if s is not None:
warnings.warn(
"Layer-specific parameter '%s' contradicts"
"ensemble-wide settings. Ignoring." % f,
LayerSpecificationWarning)
| Source File: utils.py From texar with Apache License 2.0 | 5 votes |
def check_or_get_instance_with_redundant_kwargs(
ins_or_class_or_name, kwargs, module_paths=None, classtype=None):
"""Returns a class instance and checks types.
Only those keyword arguments in :attr:`kwargs` that are included in the
class construction method are used.
Args:
ins_or_class_or_name: Can be of 3 types:
- A class to instantiate.
- A string of the name or module path to a class to \
instantiate.
- The class instance to check types.
kwargs (dict): Keyword arguments for the class constructor.
module_paths (list, optional): Paths to candidate modules to
search for the class. This is used if the class cannot be
located solely based on :attr:`class_name`. The first module
in the list that contains the class is used.
classtype (optional): A (list of) classes of which the instance must
be an instantiation.
Raises:
ValueError: If class is not found based on :attr:`class_name` and
:attr:`module_paths`.
ValueError: If :attr:`kwargs` contains arguments that are invalid
for the class construction.
TypeError: If the instance is not an instantiation of
:attr:`classtype`.
"""
ret = ins_or_class_or_name
if is_str(ret) or isinstance(ret, type):
ret = get_instance_with_redundant_kwargs(ret, kwargs, module_paths)
if classtype is not None:
if not isinstance(ret, classtype):
raise TypeError(
"An instance of {} is expected. Got: {}".format(classtype, ret))
return ret
| Source File: argument_nodes.py From cmake_format with GNU General Public License v3.0 | 5 votes |
def check_required_kwargs(self, lint_ctx, required_kwargs):
for kwargnode in self.kwarg_groups:
required_kwargs.pop(get_normalized_kwarg(kwargnode.keyword.token), None)
if required_kwargs:
location = self.get_location()
for token in self.get_semantic_tokens():
location = token.get_location()
break
# NOTE(josh): inner sorted() needed for stable sort.
missing_kwargs = sorted(
(lintid, word) for word, lintid in sorted(required_kwargs.items()))
for lintid, word in missing_kwargs:
lint_ctx.record_lint(lintid, word, location=location)
| Source File: random_render.py From 3d-dl with MIT License | 5 votes |
def check_required_kwargs(kwarg_dict, kw_list):
"""
Checks that any argument given in kw_list has an corresponding entry
in the kwarg_dict
:param kwarg_dict: Dictionary which entries are the only allowed values
:param kw_list: A list of arguments to check
:return void: If problem, raise KeyError(), otherwise return void
"""
for kw in kw_list:
if not kw in kwarg_dict.keys():
raise KeyError()
| Source File: habanero_utils.py From habanero with MIT License | 5 votes |
def check_kwargs(keys, kwargs):
for x in range(len(keys)):
if keys[x] in kwargs.keys():
mssg = "The %s parameter is not allowed with this method" % keys[x]
raise Exception(mssg)
| Source File: utils.py From texar-pytorch with Apache License 2.0 | 5 votes |
def check_or_get_instance_with_redundant_kwargs(
ins_or_class_or_name: Union[Type[T], T, str], kwargs: Kwargs,
module_paths: Optional[List[str]] = None,
classtype: Optional[Type[T]] = None) -> T:
r"""Returns a class instance and checks types.
Only those keyword arguments in :attr:`kwargs` that are included in the
class construction method are used.
Args:
ins_or_class_or_name: Can be of 3 types:
- A class to instantiate.
- A string of the name or module path to a class to instantiate.
- The class instance to check types.
kwargs (dict): Keyword arguments for the class constructor.
module_paths (list, optional): Paths to candidate modules to
search for the class. This is used if the class cannot be
located solely based on :attr:`class_name`. The first module
in the list that contains the class is used.
classtype (optional): A (list of) classes of which the instance must
be an instantiation.
Raises:
ValueError: If class is not found based on :attr:`class_name` and
:attr:`module_paths`.
ValueError: If :attr:`kwargs` contains arguments that are invalid
for the class construction.
TypeError: If the instance is not an instantiation of
:attr:`classtype`.
"""
ret = ins_or_class_or_name
if isinstance(ret, (str, type)):
ret = get_instance_with_redundant_kwargs(ret, kwargs, module_paths)
if classtype is not None:
if not isinstance(ret, classtype):
raise TypeError(
"An instance of {} is expected. Got: {}".format(classtype, ret))
return ret
| Source File: okta.py From gimme-aws-creds with Apache License 2.0 | 5 votes |
def check_kwargs(self, kwargs):
if self._use_oauth_access_token is True:
if 'headers' not in kwargs:
kwargs['headers'] = {}
kwargs['headers']['Authorization'] = "Bearer {}".format(self._oauth_access_token)
if self._use_oauth_id_token is True:
if 'headers' not in kwargs:
kwargs['headers'] = {}
kwargs['headers']['Authorization'] = "Bearer {}".format(self._oauth_access_token)
return kwargs
| Source File: utils.py From fooof with Apache License 2.0 | 5 votes |
def check_plot_kwargs(plot_kwargs, defaults):
"""Check plot keyword arguments, using default values for any missing parameters.
Parameters
----------
plot_kwargs : dict or None
Keyword arguments for a plot call.
defaults : dict
Any arguments, and their default values, to check and update in 'plot_kwargs'.
Returns
-------
plot_kwargs : dict
Keyword arguments for a plot call.
Notes
-----
If the input for `plot_kwargs` is None, then `defaults` is returned as `plot_kwargs`.
"""
if not plot_kwargs:
return defaults
for key, value in resolve_aliases(defaults, PLT_ALIASES).items():
if key not in resolve_aliases(plot_kwargs, PLT_ALIASES):
plot_kwargs[key] = value
return plot_kwargs
| Source File: utils.py From MultiPlanarUNet with MIT License | 5 votes |
def check_kwargs(kwargs, allowed, func=None):
s = ("Function '{}': ".format(func.__name__)) if func is not None else ""
for param in kwargs:
if param not in allowed:
raise RuntimeError("{}Unexpected parameter '{}' passed.".
format(s, param))
| Source File: utility.py From msticpy with MIT License | 5 votes |
def check_kwargs(supplied_args: Dict[str, Any], legal_args: List[str]):
"""
Check all kwargs names against a list.
Parameters
----------
supplied_args : Dict[str, Any]
Arguments to check
legal_args : List[str]
List of possible arguments.
Raises
------
NameError
If any of the arguments are not legal. If the an arg is
a close match to one or more `legal_args`, these are
returned in the exception.
"""
name_errs = []
for name in supplied_args:
try:
check_kwarg(name, legal_args)
except NameError as err:
name_errs.append(err)
if name_errs:
raise NameError(name_errs)
| Source File: sputils.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def check_reshape_kwargs(kwargs):
"""Unpack keyword arguments for reshape function.
This is useful because keyword arguments after star arguments are not
allowed in Python 2, but star keyword arguments are. This function unpacks
'order' and 'copy' from the star keyword arguments (with defaults) and
throws an error for any remaining.
"""
order = kwargs.pop('order', 'C')
copy = kwargs.pop('copy', False)
if kwargs: # Some unused kwargs remain
raise TypeError('reshape() got unexpected keywords arguments: {}'
.format(', '.join(kwargs.keys())))
return order, copy
| Source File: timeline.py From ttkwidgets with GNU General Public License v3.0 | 4 votes |
def check_marker_kwargs(self, kwargs):
"""
Check the types of the keyword arguments for marker creation
:param kwargs: dictionary of options for marker creation
:type kwargs: dict
:raises: TypeError, ValueError
"""
text = kwargs.get("text", "")
if not isinstance(text, str) and text is not None:
raise TypeError("text argument is not of str type")
for color in (item for item in (prefix + color for prefix in ["active_", "hover_", ""]
for color in ["background", "foreground", "outline"])):
value = kwargs.get(color, "")
if value == "default":
continue
if not isinstance(value, str):
raise TypeError("{} argument not of str type".format(color))
font = kwargs.get("font", ("default", 10))
if (not isinstance(font, tuple) or not len(font) > 0 or not isinstance(font[0], str)) and font != "default":
raise ValueError("font argument is not a valid font tuple")
for border in (prefix + "border" for prefix in ["active_", "hover_", ""]):
border_v = kwargs.get(border, 0)
if border_v == "default":
continue
if not isinstance(border_v, int) or border_v < 0:
raise ValueError("{} argument is not of int type or smaller than zero".format(border))
iid = kwargs.get("iid", "-1")
if not isinstance(iid, str):
raise TypeError("iid argument not of str type")
if iid == "":
raise ValueError("iid argument empty string")
for boolean_arg in ["move", "category_change", "allow_overlap", "snap_to_ticks"]:
value = kwargs.get(boolean_arg, False)
if value == "default":
continue
if not isinstance(value, bool):
raise TypeError("{} argument is not of bool type".format(boolean_arg))
tags = kwargs.get("tags", ())
if not isinstance(tags, tuple):
raise TypeError("tags argument is not of tuple type")
for tag in tags:
if not isinstance(tag, str):
raise TypeError("one or more values in tags argument is not of str type")
if tag not in self._tags:
raise ValueError("unknown tag in tags argument")
