function callable_name
Extracts and returns a meaningful string name from various types of callable objects including functions, methods, classes, generators, and partial functions.
/tf/active/vicechatdev/patches/util.py
498 - 520
moderate
Purpose
This utility function provides a robust way to obtain human-readable names from different callable types in Python. It handles special cases like ParameterizedFunction classes, Parameterized objects with operations, partial functions, regular functions, methods, and generators. It's particularly useful for debugging, logging, or displaying callable information in user interfaces where you need a consistent way to identify different types of callables.
Source Code
def callable_name(callable_obj):
"""
Attempt to return a meaningful name identifying a callable or generator
"""
try:
if (isinstance(callable_obj, type)
and issubclass(callable_obj, param.ParameterizedFunction)):
return callable_obj.__name__
elif (isinstance(callable_obj, param.Parameterized)
and 'operation' in callable_obj.param):
return callable_obj.operation.__name__
elif isinstance(callable_obj, partial):
return str(callable_obj)
elif inspect.isfunction(callable_obj): # functions and staticmethods
return callable_obj.__name__
elif inspect.ismethod(callable_obj): # instance and class methods
return callable_obj.__func__.__qualname__.replace('.__call__', '')
elif isinstance(callable_obj, types.GeneratorType):
return callable_obj.__name__
else:
return type(callable_obj).__name__
except Exception:
return str(callable_obj)
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
callable_obj |
- | - | positional_or_keyword |
Parameter Details
callable_obj: Any callable object (function, method, class, generator, partial function, or param.Parameterized object). Can be a regular function, static method, instance method, class method, generator, functools.partial object, param.ParameterizedFunction subclass, or param.Parameterized instance with an 'operation' parameter. The function will attempt to extract the most meaningful name from whatever type is provided.
Return Value
Returns a string representing the name of the callable. For functions and static methods, returns __name__. For methods, returns the qualified name without '.__call__'. For ParameterizedFunction classes, returns the class __name__. For Parameterized objects with 'operation', returns the operation's __name__. For partial functions, returns the string representation. For generators, returns __name__. For other types, returns the type name. If any exception occurs during name extraction, returns str(callable_obj) as a fallback.
Dependencies
paraminspecttypesfunctools
Required Imports
import param
import inspect
import types
from functools import partial
Usage Example
import param
import inspect
import types
from functools import partial
def callable_name(callable_obj):
try:
if (isinstance(callable_obj, type)
and issubclass(callable_obj, param.ParameterizedFunction)):
return callable_obj.__name__
elif (isinstance(callable_obj, param.Parameterized)
and 'operation' in callable_obj.param):
return callable_obj.operation.__name__
elif isinstance(callable_obj, partial):
return str(callable_obj)
elif inspect.isfunction(callable_obj):
return callable_obj.__name__
elif inspect.ismethod(callable_obj):
return callable_obj.__func__.__qualname__.replace('.__call__', '')
elif isinstance(callable_obj, types.GeneratorType):
return callable_obj.__name__
else:
return type(callable_obj).__name__
except Exception:
return str(callable_obj)
# Example usage:
def my_function():
pass
class MyClass:
def my_method(self):
pass
print(callable_name(my_function)) # Output: 'my_function'
print(callable_name(MyClass().my_method)) # Output: 'MyClass.my_method'
print(callable_name(partial(my_function))) # Output: 'functools.partial(<function my_function at ...>)'
print(callable_name(lambda x: x)) # Output: '<lambda>'
Best Practices
- This function is designed to never raise an exception - it has a catch-all exception handler that returns str(callable_obj) as a fallback
- The function handles param.ParameterizedFunction and param.Parameterized objects specially, so ensure the param library is available if working with these types
- For methods, the function removes '.__call__' from the qualified name to provide cleaner output
- The function returns different levels of detail depending on the callable type - be aware that partial functions return full string representations which may be verbose
- Use this function when you need consistent string representations of callables across different types for logging, debugging, or UI display purposes
- The function checks types in a specific order (ParameterizedFunction, Parameterized with operation, partial, function, method, generator, then fallback to type name), so more specific types are handled first
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function argspec 48.4% similar
-
class Generator 46.0% similar
-
function get_document_type_name 44.8% similar
-
function get_method_owner 44.1% similar
-
function extract_conclusion_text_for_pdf 42.0% similar