Function Signatures¶
Function signatures are represented by the Signature class.
Function parameters are represented by the Parameter class.
Signatures can be created through the signature() function or the Signature class’s various from_X methods - Signature.from_callable(), Signature.from_signature().
- class introspection.Signature¶
Bases:
SignatureAn
inspect.Signaturesubclass that represents a function’s parameter signature and return annotation.Instances of this class are immutable.
- Variables
parameters – An
OrderedDictofParameterobjectsreturn_annotation – The annotation for the function’s return value
- __init__(parameters=None, return_annotation=inspect.Signature.empty, validate_parameters=True)¶
- Parameters
parameters (
Union[Iterable[Parameter],Dict[str,Parameter],None], default:None) – A list or dict ofParameterobjectsreturn_annotation (
Any, default:inspect.Signature.empty) – The annotation for the function’s return valuevalidate_parameters (
bool, default:True) – Whether to check if the signature is valid
- classmethod from_signature(signature, parameter_type=introspection.Parameter)¶
Creates a new
Signatureinstance from aninspect.Signatureinstance.Changed in version 1.4:
param_typeparameter renamed toparameter_type.- Parameters
signature (
Signature) – Aninspect.Signatureinstanceparameter_type (
type, default:introspection.Parameter) – The class to use for the signature’s parameters
- Return type
Signature- Returns
A new
Signatureinstance
- classmethod from_callable(callable_, parameter_type=introspection.Parameter, follow_wrapped=True, use_signature_db=True)¶
Returns a matching
Signatureinstance for the givencallable_.Because the signatures of builtin functions often cannot be determined (at least in older python versions), this function contains a database of signatures for builtin functions. These signatures contain much more detail than
inspect.signature()would provide - like type annotations and default values ofParameter.missing.Pass
use_signature_db=Falseif you wish to bypass the signature database.Changed in version 1.1: Returns more accurate signatures for builtin functions. Also added missing “value” parameter for
setattr.New in version 1.2: Added
use_signature_dbparameter.Changed in version 1.2: Signature database updated for python 3.9.
Changed in version 1.4: Signature database updated for python 3.10.
param_typeparameter renamed toparameter_type.- Parameters
callable_ – A function or any other callable object
parameter_type (
Type[Parameter], default:introspection.Parameter) – The class to use for the signature’s parametersfollow_wrapped (
bool, default:True) – Whether to unwrap decorated callablesuse_signature_db (
bool, default:True) – Whether to look up the signature
- Return type
Signature- Returns
A corresponding
Signatureinstance- Raises
TypeError – If
callable_isn’t a callable objectValueError – If the signature can’t be determined (can happen for functions defined in C extensions)
- classmethod for_method(class_or_mro, method_name, *, parameter_type=introspection.Parameter)¶
Creates a combined signature for the method in the given class and all parent classes, assuming that all *args and **kwargs are passed to the parent method.
Example:
class A: def method(self, foo: int = 3) -> None: pass class B(A): def method(self, *args, bar: bool = True, **kwargs): return super().method(*args, **kwargs) print(Signature.for_method(B, 'method')) # (self, foo: int = 3, *, bar: bool = True) -> None
New in version 1.5.
- without_parameters(*params_to_remove)¶
Returns a copy of this signature with some parameters removed.
Parameters can be referenced by the following things:
index
name
kind
Example:
>>> sig = Signature([ ... Parameter('foo'), ... Parameter('bar'), ... Parameter('baz'), ... ]) >>> sig.without_parameters(0, 'baz') <Signature (bar)>
Changed in version 1.5: Parameters can now be referenced by kind.
- Parameters
parameters – Names or indices of the parameters to remove
- Return type
Signature- Returns
A copy of this signature without the given parameters
- property parameter_list: List[Parameter]¶
Returns a list of the signature’s parameters.
- Return type
List[Parameter]
- property has_return_annotation: bool¶
Returns whether the signature’s return annotation is not
Signature.empty.- Return type
- property num_required_arguments: int¶
Returns the number of required arguments, i.e. arguments with no default value.
- Return type
- bind(*args, **kwargs)¶
Similar to
inspect.Signature.bind(), but returns aintrospection.BoundArgumentsobject.- Return type
BoundArguments
- bind_partial(*args, **kwargs)¶
Similar to
inspect.Signature.bind_partial(), but returns aintrospection.BoundArgumentsobject.- Return type
BoundArguments
- to_string(implicit_typing=False)¶
Returns a string representation of this signature.
Example:
>>> Signature([ ... Parameter('nums', Parameter.VAR_POSITIONAL, annotation=int) ... ], return_annotation=int).to_string() '(*nums: int) -> int'
- class introspection.Parameter¶
Bases:
ParameterAn
inspect.Parametersubclass that represents a function parameter.Instances of this class are immutable.
This class adds a new special value for the
defaultattribute:Parameter.missing.- Variables
name – The parameter’s name
kind – The parameter’s kind. See
inspect.Parameter.kindfor details.default – The parameter’s default value or
inspect.Parameter.emptyannotation – The parameter’s type annotation
- missing¶
A special class-level marker that can be used to specify that the parameter is optional, but doesn’t have a (known) default value.
This is commonly used by signatures for builtin functions. For example, the signature of the
rangefunction can be represented as>>> Signature([ ... Parameter('start', Parameter.POSITIONAL_ONLY), ... Parameter('stop', Parameter.POSITIONAL_ONLY, default=Parameter.missing), ... Parameter('step', Parameter.POSITIONAL_ONLY, default=Parameter.missing), ... ]) <Signature (start[, stop[, step]], /)>
- __init__(name=None, kind=inspect.Parameter.POSITIONAL_OR_KEYWORD, default=inspect.Parameter.empty, annotation=inspect.Parameter.empty)¶
- Parameters
name (str) – The parameter’s name
kind (
Any, default:inspect.Parameter.POSITIONAL_OR_KEYWORD) – The parameter’s kind. Seeinspect.Parameter.kindfor details.default (
Any, default:inspect.Parameter.empty) – The parameter’s default value, or one of the special valuesinspect.Parameter.emptyandParameter.missingannotation (
Any, default:inspect.Parameter.empty) – The parameter’s type annotation
- classmethod from_parameter(parameter)¶
Creates a new
Parameterinstance from aninspect.Parameterinstance.- Parameters
parameter (
Parameter) – Aninspect.Parameterinstance- Return type
Parameter- Returns
A new
Parameterinstance
- property has_annotation: bool¶
Returns whether the parameter’s
annotationis notParameter.empty.- Return type
- property is_vararg: bool¶
Returns a boolean indicating whether this parameter accepts a variable number of arguments; i.e. whether the parameter’s kind is
inspect.Parameter.VAR_POSITIONALorinspect.Parameter.VAR_KEYWORD.- Return type
- property is_optional: bool¶
Returns a boolean indicating whether this parameter can be omitted or requires an argument.
Returns
Trueif the parameter has a default value or is a vararg.- Return type
- to_string(implicit_typing=False)¶
Returns a string representation of this parameter, similar to how parameters are written in function signatures.
Examples:
>>> Parameter('foo', Parameter.VAR_POSITIONAL).to_string() '*foo' >>> Parameter('foo', annotation=int, default=3).to_string() 'foo: int = 3'
- class introspection.BoundArguments¶
Bases:
BoundArguments,MutableMappingSubclass of
inspect.BoundArgumentswith additional features.New in version 1.4.
- classmethod from_bound_arguments(bound_args)¶
Creates a new
BoundArgumentsinstance from ainspect.BoundArgumentsinstance.- Parameters
bound_args (
BoundArguments) – Aninspect.BoundArgumentsinstance- Return type
BoundArguments- Returns
A new
BoundArgumentsinstance
- get_missing_parameter_names(include_optional_parameters=False)¶
Returns the set of parameter names that were omitted in the call to
Signature.bind_partial().If
include_optional_parametersisTrue, parameters with a default value are included in the output.*argsand**kwargsare never included in the output.Examples:
>>> signature (foo, bar, *args, baz=3) >>> bound_args = signature.bind_partial(1) >>> bound_args.get_missing_parameter_names() {'bar'} >>> bound_args.get_missing_parameter_names(True) {'bar', 'baz'}
New in version 1.5.
- to_varargs(prefer='kwargs')¶
Converts the arguments into an
(args, kwargs)tuple.Example:
>>> signature = Signature.from_callable(lambda a, *b, c: 0) >>> bound_args = signature.bind(1, c=2) >>> bound_args.to_varargs(prefer='args') ([1], {'c': 2}) >>> bound_args.to_varargs(prefer='kwargs') ([], {'a': 1, 'c': 2})
- introspection.signature(*args, **kwargs)¶
Shorthand for
Signature.from_callable().