🔍 Code Extractor

function _has_generic_or_protocol_as_origin

Maturity: 37

Internal function that inspects the call stack to determine if the caller is from typing.py and has Generic or Protocol as the origin parameter.

File:
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/typing_extensions.py
Lines:
3143 - 3159
Complexity:
moderate

Purpose

This is a defensive utility function used to detect whether the current execution context is within the typing module and specifically checking if the 'origin' local variable in the caller's frame is typing.Generic or Protocol. It's designed to handle edge cases in type checking or validation scenarios where behavior needs to differ based on whether Generic or Protocol types are being processed. The function errs on the side of leniency by returning False when it cannot safely determine the context.

Source Code

def _has_generic_or_protocol_as_origin() -> bool:
    try:
        frame = sys._getframe(2)
    # - Catch AttributeError: not all Python implementations have sys._getframe()
    # - Catch ValueError: maybe we're called from an unexpected module
    #   and the call stack isn't deep enough
    except (AttributeError, ValueError):
        return False  # err on the side of leniency
    else:
        # If we somehow get invoked from outside typing.py,
        # also err on the side of leniency
        if frame.f_globals.get("__name__") != "typing":
            return False
        origin = frame.f_locals.get("origin")
        # Cannot use "in" because origin may be an object with a buggy __eq__ that
        # throws an error.
        return origin is typing.Generic or origin is Protocol or origin is typing.Protocol

Return Value

Type: bool

Returns a boolean value: True if the function is called from within the typing module (frame 2 levels up) and the 'origin' local variable in that frame is typing.Generic or Protocol; False in all other cases including when the call stack is too shallow, sys._getframe() is unavailable, or the caller is not from typing.py.

Dependencies

  • sys
  • typing

Required Imports

import sys
import typing

Usage Example

# This function is typically used internally within type checking libraries
# It's not meant for direct external use, but here's how it would be called:

import sys
import typing
from typing import Protocol

def _has_generic_or_protocol_as_origin() -> bool:
    try:
        frame = sys._getframe(2)
    except (AttributeError, ValueError):
        return False
    else:
        if frame.f_globals.get("__name__") != "typing":
            return False
        origin = frame.f_locals.get("origin")
        return origin is typing.Generic or origin is Protocol or origin is typing.Protocol

# Example usage (would typically be called from within typing module context):
result = _has_generic_or_protocol_as_origin()
print(f"Has Generic or Protocol as origin: {result}")
# Expected output when called outside typing.py: False

Best Practices

  • This is an internal utility function not intended for public API use
  • The function uses sys._getframe() which is implementation-specific and may not be available in all Python implementations
  • The function intentionally returns False (lenient behavior) when it cannot determine the context safely
  • Uses identity checks (is) instead of equality (==) to avoid triggering potentially buggy __eq__ implementations
  • Checks specifically for frame depth of 2, meaning it expects to be called from a function that is itself called from typing.py
  • Should only be used in contexts where you need to detect typing module internals during runtime type processing

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function _caller 50.6% similar

    Retrieves the module name of the calling function at a specified stack depth, with fallback mechanisms for different Python platforms.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/typing_extensions.py
  • function _get_protocol_attrs 48.2% similar

    Extracts all non-private attribute names from a Protocol class by traversing its method resolution order (MRO), excluding special attributes and base Protocol/Generic classes.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/typing_extensions.py
  • function _is_unpacked_typevartuple 44.1% similar

    Checks if a given type annotation represents an unpacked TypeVarTuple (i.e., *Ts syntax in type hints).

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/typing_extensions.py
  • function _set_module 44.1% similar

    Internal utility function that sets the __module__ attribute of a type variable-like object to the calling module's name for proper pickling support.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/typing_extensions.py
  • function _set_default 40.5% similar

    Internal utility function that sets default value metadata on a type parameter object by adding a has_default method and __default__ attribute.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/typing_extensions.py
← Back to Browse