function _caller
Retrieves the module name of the calling function at a specified stack depth, with fallback mechanisms for different Python platforms.
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/typing_extensions.py
615 - 624
moderate
Purpose
This utility function inspects the call stack to determine which module called the current function. It's designed with platform compatibility in mind, providing multiple fallback strategies for platforms that may not support certain introspection features. The function attempts to use sys._getframemodulename() first (Python 3.11+), then falls back to sys._getframe() for older versions, and returns None if neither is available. This is commonly used in logging, debugging, or framework code that needs to identify the calling context.
Source Code
def _caller(depth=1, default='__main__'):
try:
return sys._getframemodulename(depth + 1) or default
except AttributeError: # For platforms without _getframemodulename()
pass
try:
return sys._getframe(depth + 1).f_globals.get('__name__', default)
except (AttributeError, ValueError): # For platforms without _getframe()
pass
return None
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
depth |
- | 1 | positional_or_keyword |
default |
- | '__main__' | positional_or_keyword |
Parameter Details
depth: Integer specifying how many stack frames to traverse upward from the current frame. Default is 1, meaning the immediate caller. Increase this value to look further up the call stack. The function adds 1 to this value internally to account for its own frame.
default: String value to return if the module name cannot be determined but a frame exists. Defaults to '__main__', which is the typical name for the main execution module. This provides a sensible fallback for scripts run directly.
Return Value
Returns a string containing the module name of the caller at the specified depth (e.g., 'mymodule', '__main__', 'package.submodule'). Returns the 'default' parameter value if the frame exists but has no __name__. Returns None if stack frame introspection is not available on the platform or if the specified depth exceeds the call stack depth (ValueError).
Dependencies
sys
Required Imports
import sys
Usage Example
import sys
def _caller(depth=1, default='__main__'):
try:
return sys._getframemodulename(depth + 1) or default
except AttributeError:
pass
try:
return sys._getframe(depth + 1).f_globals.get('__name__', default)
except (AttributeError, ValueError):
pass
return None
# Example usage in a logging context
def my_function():
caller_module = _caller()
print(f"Called from module: {caller_module}")
return caller_module
# When called from main script
if __name__ == '__main__':
result = my_function() # Will print: Called from module: __main__
# Example with custom depth
def level1():
return level2()
def level2():
# Get the module name 2 levels up (level1's caller)
return _caller(depth=2)
result = level1() # Returns the module name of whoever called level1()
Best Practices
- Be aware that sys._getframemodulename() is only available in Python 3.11+, so this function provides backward compatibility
- The depth parameter should be carefully chosen based on your call stack structure; incorrect depth values may return unexpected modules or None
- This function may return None on platforms without frame introspection support (rare but possible in embedded Python)
- Avoid using this in performance-critical code as stack frame inspection has overhead
- The function is typically used for debugging, logging, or framework internals rather than application logic
- When using in nested function calls, remember that depth is relative to where _caller is invoked, not where it's defined
- Consider caching results if calling repeatedly with the same depth in a hot code path
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function _set_module 55.0% similar
-
function _has_generic_or_protocol_as_origin 50.6% similar
-
function _get_protocol_attrs 32.7% similar
-
class Call 32.0% similar
-
function get_mime_type 31.8% similar