diff options
author | Matthias Baumgartner <dev@igsor.net> | 2022-12-22 20:35:15 +0100 |
---|---|---|
committer | Matthias Baumgartner <dev@igsor.net> | 2022-12-22 20:35:15 +0100 |
commit | 9ab60f915fa53ae2ac2cf06b2f68138ffaa534d4 (patch) | |
tree | e6290053c00e06fda9e41ac0a602ff53d91a38ac /bsfs/utils/commons.py | |
parent | e94368c75468e3e94382b12705e55d396249eaca (diff) | |
parent | ca7ee6c59d2eb3f4ec4d16e392d12d946cd85e4d (diff) | |
download | bsfs-9ab60f915fa53ae2ac2cf06b2f68138ffaa534d4.tar.gz bsfs-9ab60f915fa53ae2ac2cf06b2f68138ffaa534d4.tar.bz2 bsfs-9ab60f915fa53ae2ac2cf06b2f68138ffaa534d4.zip |
Merge branch 'mb/filter' into develop
Diffstat (limited to 'bsfs/utils/commons.py')
-rw-r--r-- | bsfs/utils/commons.py | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/bsfs/utils/commons.py b/bsfs/utils/commons.py index bad2fe0..e9f0b7f 100644 --- a/bsfs/utils/commons.py +++ b/bsfs/utils/commons.py @@ -5,10 +5,12 @@ A copy of the license is provided with the project. Author: Matthias Baumgartner, 2022 """ # imports +from collections import abc import typing # exports __all__: typing.Sequence[str] = ( + 'normalize_args', 'typename', ) @@ -19,5 +21,37 @@ def typename(obj) -> str: """Return the type name of *obj*.""" return type(obj).__name__ +# argument type in `normalize_args`. +ArgType = typing.TypeVar('ArgType') # pylint: disable=invalid-name # type vars don't follow the usual convention + +def normalize_args( + *args: typing.Union[ArgType, typing.Iterable[ArgType], typing.Iterator[ArgType]] + ) -> typing.Tuple[ArgType, ...]: + """Arguments to a function can be passed as individual arguments, list-like + structures, or iterables. This function processes any of these styles and + returns a tuple of the respective items. Typically used within a function + provide a flexible interface but sill have parameters in a normalized form. + + Examples: + + >>> normalize_args(0,1,2) + (1,2,3) + >>> normalize_args([0,1,2]) + (1,2,3) + >>> normalize_args(range(3)) + (1,2,3) + + """ + if len(args) == 0: # foo() + return tuple() + if len(args) > 1: # foo(0, 1, 2) + return tuple(args) # type: ignore [arg-type] # we assume that argument styles (arg vs. iterable) are not mixed. + if isinstance(args[0], abc.Iterator): # foo(iter([0,1,2])) + return tuple(args[0]) + if isinstance(args[0], abc.Iterable) and not isinstance(args[0], str): # foo([0, 1, 2]) + return tuple(args[0]) + # foo(0) + return (args[0], ) # type: ignore [return-value] # if args[0] is a str, we assume that ArgType was str. + ## EOF ## |