function _set_default
Internal utility function that sets default value metadata on a type parameter object by adding a has_default method and __default__ attribute.
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/typing_extensions.py
1646 - 1648
simple
Purpose
This function is used internally to configure type parameter objects (like TypeVar, ParamSpec, or TypeVarTuple) with default value information. It modifies the type parameter in-place by adding a lambda function to check if a default exists and storing the default value itself. This is part of Python's type system implementation for handling generic type parameters with defaults.
Source Code
def _set_default(type_param, default):
type_param.has_default = lambda: default is not NoDefault
type_param.__default__ = default
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
type_param |
- | - | positional_or_keyword |
default |
- | - | positional_or_keyword |
Parameter Details
type_param: A type parameter object (TypeVar, ParamSpec, or TypeVarTuple) that will be modified to include default value information. This object is mutated in-place.
default: The default value to assign to the type parameter. Can be any value or the special sentinel value NoDefault to indicate no default is provided. When NoDefault is passed, has_default() will return False.
Return Value
This function returns None (implicitly). It operates by side-effect, modifying the type_param object in-place by adding the has_default method and __default__ attribute.
Usage Example
# This is an internal function typically used within the typing module implementation
# Example of how it might be used:
class NoDefault:
pass
def _set_default(type_param, default):
type_param.has_default = lambda: default is not NoDefault
type_param.__default__ = default
# Create a mock type parameter object
class MockTypeParam:
pass
type_param = MockTypeParam()
# Set a default value
_set_default(type_param, int)
print(type_param.has_default()) # True
print(type_param.__default__) # <class 'int'>
# Set no default
_set_default(type_param, NoDefault)
print(type_param.has_default()) # False
print(type_param.__default__) # <class 'NoDefault'>
Best Practices
- This is an internal implementation function and should not be called directly by user code
- The function mutates the type_param object in-place, so be aware of side effects
- Always ensure NoDefault sentinel is properly defined before using this function
- The has_default method is implemented as a lambda that captures the default value via closure
- This function is typically used during type parameter initialization in the typing module
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class _DefaultMixin 69.2% similar
-
function _set_module 54.0% similar
-
function IntVar 45.5% similar
-
class _TypeVarLikeMeta 43.8% similar
-
function _has_generic_or_protocol_as_origin 40.5% similar