function argspec
Extracts and normalizes function argument specifications from various callable types, removing implicit 'self' or 'cls' parameters from methods.
/tf/active/vicechatdev/patches/util.py
391 - 425
moderate
Purpose
This function provides a unified interface for introspecting the argument specifications of different callable types in Python, including regular functions, static methods, instance methods, class methods, partial functions, and callable objects. It normalizes the argument list by removing implicit parameters (self/cls) that users don't need to provide when calling methods, making it useful for dynamic function analysis, documentation generation, and runtime introspection.
Source Code
def argspec(callable_obj):
"""
Returns an ArgSpec object for functions, staticmethods, instance
methods, classmethods and partials.
Note that the args list for instance and class methods are those as
seen by the user. In other words, the first argument which is
conventionally called 'self' or 'cls' is omitted in these cases.
"""
if (isinstance(callable_obj, type)
and issubclass(callable_obj, param.ParameterizedFunction)):
# Parameterized function.__call__ considered function in py3 but not py2
spec = inspect.getfullargspec(callable_obj.__call__)
args = spec.args[1:]
elif inspect.isfunction(callable_obj): # functions and staticmethods
spec = inspect.getfullargspec(callable_obj)
args = spec.args
elif isinstance(callable_obj, partial): # partials
arglen = len(callable_obj.args)
spec = inspect.getfullargspec(callable_obj.func)
args = [arg for arg in spec.args[arglen:] if arg not in callable_obj.keywords]
elif inspect.ismethod(callable_obj): # instance and class methods
spec = inspect.getfullargspec(callable_obj)
args = spec.args[1:]
elif isinstance(callable_obj, type) and issubclass(callable_obj, param.Parameterized):
return argspec(callable_obj.__init__)
elif callable(callable_obj): # callable objects
return argspec(callable_obj.__call__)
else:
raise ValueError("Cannot determine argspec for non-callable type.")
return inspect.FullArgSpec(args=args,
varargs=spec.varargs,
varkw=get_keywords(spec),
defaults=spec.defaults, kwonlyargs=None, kwonlydefaults=None, annotations=None)
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
callable_obj |
- | - | positional_or_keyword |
Parameter Details
callable_obj: Any callable Python object including functions, methods (instance, class, static), partial functions, ParameterizedFunction subclasses, Parameterized subclasses, or objects with a __call__ method. The function will introspect this object to extract its argument specification.
Return Value
Returns an inspect.FullArgSpec object containing the normalized argument specification with fields: args (list of argument names excluding self/cls), varargs (name of *args parameter or None), varkw (name of **kwargs parameter or None), defaults (tuple of default values or None), and kwonlyargs, kwonlydefaults, annotations set to None. For partial functions, arguments already bound are excluded from the args list.
Dependencies
inspectparamfunctools
Required Imports
import inspect
import param
from functools import partial
Usage Example
import inspect
import param
from functools import partial
# Assuming get_keywords helper function exists
def get_keywords(spec):
return spec.varkw
def example_function(a, b, c=10, *args, **kwargs):
pass
class MyClass:
def instance_method(self, x, y=5):
pass
@classmethod
def class_method(cls, z):
pass
# Get argspec for regular function
spec1 = argspec(example_function)
print(spec1.args) # ['a', 'b', 'c']
print(spec1.defaults) # (10,)
# Get argspec for instance method (self removed)
obj = MyClass()
spec2 = argspec(obj.instance_method)
print(spec2.args) # ['x', 'y']
# Get argspec for partial function
partial_func = partial(example_function, 1, 2)
spec3 = argspec(partial_func)
print(spec3.args) # ['c']
Best Practices
- This function requires a helper function 'get_keywords' to be defined in the same module to extract keyword arguments from the spec
- The function handles param.ParameterizedFunction and param.Parameterized types specially, so ensure the param library is available if working with these types
- For partial functions, the returned argspec excludes both positional arguments already bound and keyword arguments present in the partial's keywords dictionary
- The function recursively calls itself for Parameterized classes (via __init__) and callable objects (via __call__), so be aware of potential infinite recursion with circular callable references
- The returned FullArgSpec has kwonlyargs, kwonlydefaults, and annotations always set to None, so don't rely on these fields for Python 3 keyword-only arguments
- Raises ValueError if the input is not callable, so wrap calls in try-except if handling unknown types
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function callable_name 48.4% similar
-
function get_spec 45.4% similar
-
function parse_arguments_v1 42.2% similar
-
function parse_arguments 41.3% similar
-
function validate_dynamic_argspec 38.7% similar