scverse_misc.arg_alias

Contents

scverse_misc.arg_alias#

scverse_misc.arg_alias(argname)#

Decorator to specify aliases for function arguments that accept a fixed set of values.

If a function argument accepts a fixed set of values that partitions into multiple equivalence classes (i.e. several values are aliased to the same behavior), this decorator converts each equivalence class into its chosen canonical representation before passing it on to the function. This eliminates the need for the function to perform validation and conversion itself, the function can be certain that it always gets the canonical representation.

The rules are encoded in the type hint for the aliased argument. If there is only a single set of aliases, the type hint must be a Literal with the canonical representation as first argument followed by its aliases. If there are multiple sets of aliases, that is multiple semantically different values that the function accepts, the type hint must be a Union of Literal s, where each Literal follows the same rules as above: The canonical representation is the first argument followed by its aliases.

Parameters:

argname (str) – The name of the argument to alias.

Return type:

Callable[[Callable[[ParamSpec(P)], TypeVar(R)]], Callable[[ParamSpec(P)], TypeVar(R)]]

Examples

>>> @axis_arg("axis")
... def foo(x: int, axis: Literal[0, "obs"]):
...     return axis
...
...
... assert foo(42, 0) == foo(42, "obs") == 0
>>> @axis_arg("axis")
... def foo(x: float, axis: Literal[0, "obs"] | Literal[1, "var", "vars"]):
...     return axis
...
...
... assert foo(42, 0) == foo(42, "obs") == 1
... assert foo(42, 1) == foo(42, "var") == foo(42, "vars") == 1