PyDocs

Nav

Development Tools

ParamSpec

typing

class · Added in 3.10
  • ParamSpec(name, *, bound=None, covariant=False, contravariant=False, infer_variance=False, default=typing.NoDefault)
Parameter specification variable.

The preferred way to construct a parameter specification is via the
dedicated syntax for generic functions, classes, and type aliases,
where the use of '**' creates a parameter specification::

    type IntFunc[**P] = Callable[P, int]

The following syntax creates a parameter specification that defaults
to a callable accepting two positional-only arguments of types int
and str:

    type IntFuncDefault[**P = [int, str]] = Callable[P, int]

For compatibility with Python 3.11 and earlier, ParamSpec objects
can also be created as follows::

    P = ParamSpec('P')
    DefaultP = ParamSpec('DefaultP', default=[int, str])

Parameter specification variables exist primarily for the benefit of
static type checkers.  They are used to forward the parameter types of
one callable to another callable, a pattern commonly found in
higher-order functions and decorators.  They are only valid when used
in ``Concatenate``, or as the first argument to ``Callable``, or as
parameters for user-defined Generics. See class Generic for more
information on generic types.

An example for annotating a decorator::

    def add_logging[**P, T](f: Callable[P, T]) -> Callable[P, T]:
        '''A type-safe decorator to add logging to a function.'''
        def inner(*args: P.args, **kwargs: P.kwargs) -> T:
            logging.info(f'{f.__name__} was called')
            return f(*args, **kwargs)
        return inner

    @add_logging
    def add_two(x: float, y: float) -> float:
        '''Add two numbers together.'''
        return x + y

Parameter specification variables can be introspected. e.g.::

    >>> P = ParamSpec("P")
    >>> P.__name__
    'P'

Note that only parameter specification variables defined in the global
scope can be pickled.
Changed in 3.12, 3.13
  • 3.12: Parameter specifications can now be declared using the type parameter syntax introduced by PEP 695.
  • 3.13: Support for default values was added.
Members of ParamSpec

_

__contravariant__
Whether the parameter specification has been explicitly marked as contravariant.
__covariant__
Whether the parameter specification has been explicitly marked as covariant.
__default__
The default value for this ParamSpec.
__infer_variance__
Whether the parameter specification’s variance should be inferred by type checkers.
__name__
The name of the parameter specification.

a

args
Represents positional arguments.

e

evaluate_default
An evaluate function corresponding to the __default__ attribute.

h

has_default
Return whether or not the parameter specification has a default value.

k

kwargs
Represents keyword arguments.
0 Examples
No examples for typing/ParamSpec.
See Also
No see-alsos for typing/ParamSpec
0 Notes
No notes for ParamSpec