本文整理匯總了Python中inspect.getargs方法的典型用法代碼示例。如果您正苦於以下問題:Python inspect.getargs方法的具體用法?Python inspect.getargs怎麽用?Python inspect.getargs使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類inspect
的用法示例。
在下文中一共展示了inspect.getargs方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: getargtxt
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargs [as 別名]
def getargtxt(obj, one_arg_per_line=True):
"""
Get the names and default values of a function's arguments
Return list with separators (', ') formatted for calltips
"""
args = getargs(obj)
if args:
sep = ', '
textlist = None
for i_arg, arg in enumerate(args):
if textlist is None:
textlist = ['']
textlist[-1] += arg
if i_arg < len(args)-1:
textlist[-1] += sep
if len(textlist[-1]) >= 32 or one_arg_per_line:
textlist.append('')
if inspect.isclass(obj) or inspect.ismethod(obj):
if len(textlist) == 1:
return None
if 'self'+sep in textlist:
textlist.remove('self'+sep)
return textlist
示例2: getargspec
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargs [as 別名]
def getargspec(obj):
"""Get the names and default values of a function's arguments.
A tuple of four things is returned: (args, varargs, varkw, defaults).
'args' is a list of the argument names (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'defaults' is an n-tuple of the default values of the last n arguments.
Modified version of inspect.getargspec from the Python Standard
Library."""
if inspect.isfunction(obj):
func_obj = obj
elif inspect.ismethod(obj):
func_obj = obj.im_func
else:
raise TypeError('arg is not a Python function')
args, varargs, varkw = inspect.getargs(func_obj.func_code)
return args, varargs, varkw, func_obj.func_defaults
#-----------------------------------------------------------------------------
# Testing functions
示例3: getargspec
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargs [as 別名]
def getargspec(obj):
"""Get the names and default values of a function's arguments.
A tuple of four things is returned: (args, varargs, varkw, defaults).
'args' is a list of the argument names (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'defaults' is an n-tuple of the default values of the last n arguments.
Modified version of inspect.getargspec from the Python Standard
Library."""
if inspect.isfunction(obj):
func_obj = obj
elif inspect.ismethod(obj):
func_obj = obj.im_func
elif hasattr(obj, '__call__'):
func_obj = obj.__call__
else:
raise TypeError('arg is not a Python function')
args, varargs, varkw = inspect.getargs(func_obj.func_code)
return args, varargs, varkw, func_obj.func_defaults
示例4: get_method_args
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargs [as 別名]
def get_method_args(target_method):
# type: (Callable) -> Tuple[Callable, Optional[inspect.Arguments]]
"""
Returns the arguments for a callable.
:param Callable target_method: A callable to retrieve arguments for
:return: A 2-tuple of the original callable and its resulting arguments
:rtype: Tuple[Callable, Optional[inspect.Arguments]]
"""
inspected_args = None
try:
inspected_args = inspect.getargs(target_method.__code__)
except AttributeError:
target_func = getattr(target_method, "__func__", None)
if target_func is not None:
inspected_args = inspect.getargs(target_func.__code__)
else:
target_func = target_method
return target_func, inspected_args
示例5: trace_function
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargs [as 別名]
def trace_function(self, func):
# type: (FunctionType) -> FunctionType
new_func = super(BirdsEye, self).trace_function(func)
code_info = self._code_infos.get(new_func.__code__)
if code_info:
return new_func
lines, start_lineno = inspect.getsourcelines(func) # type: List[Text], int
end_lineno = start_lineno + len(lines)
name = safe_qualname(func)
source_file = inspect.getsourcefile(func)
if source_file.startswith('<ipython-input'):
filename = IPYTHON_FILE_PATH
else:
filename = os.path.abspath(source_file)
traced_file = new_func.traced_file
arg_info = inspect.getargs(new_func.__code__)
arg_names = list(chain(flatten_list(arg_info[0]), arg_info[1:])) # type: List[str]
self._trace(name, filename, traced_file, new_func.__code__, typ='function',
start_lineno=start_lineno, end_lineno=end_lineno,
arg_names=arg_names)
return new_func
示例6: getargspec
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargs [as 別名]
def getargspec(func):
"""Variation of inspect.getargspec that works for more functions.
This function works for Cythonized, non-cpdef functions, which expose argspec information but
are not accepted by getargspec. It also works for Python 3 functions that use annotations, which
are simply ignored. However, keyword-only arguments are not supported.
"""
if inspect.ismethod(func):
func = func.__func__
# Cythonized functions have a .__code__, but don't pass inspect.isfunction()
try:
code = func.__code__
except AttributeError:
raise TypeError("{!r} is not a Python function".format(func))
if hasattr(code, "co_kwonlyargcount") and code.co_kwonlyargcount > 0:
raise ValueError("keyword-only arguments are not supported by getargspec()")
args, varargs, varkw = inspect.getargs(code)
return inspect.ArgSpec(args, varargs, varkw, func.__defaults__)
示例7: getargs
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargs [as 別名]
def getargs(obj):
"""Get the names and default values of a function's arguments"""
if inspect.isfunction(obj) or inspect.isbuiltin(obj):
func_obj = obj
elif inspect.ismethod(obj):
func_obj = get_meth_func(obj)
elif inspect.isclass(obj) and hasattr(obj, '__init__'):
func_obj = getattr(obj, '__init__')
else:
return []
if not hasattr(func_obj, 'func_code'):
# Builtin: try to extract info from doc
args = getargsfromdoc(func_obj)
if args is not None:
return args
else:
# Example: PyQt5
return getargsfromdoc(obj)
args, _, _ = inspect.getargs(func_obj.func_code)
if not args:
return getargsfromdoc(obj)
# Supporting tuple arguments in def statement:
for i_arg, arg in enumerate(args):
if isinstance(arg, list):
args[i_arg] = "(%s)" % ", ".join(arg)
defaults = get_func_defaults(func_obj)
if defaults is not None:
for index, default in enumerate(defaults):
args[index+len(args)-len(defaults)] += '='+repr(default)
if inspect.isclass(obj) or inspect.ismethod(obj):
if len(args) == 1:
return None
if 'self' in args:
args.remove('self')
return args
示例8: getargspec
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargs [as 別名]
def getargspec(func):
"""Get the names and default values of a function's arguments.
A tuple of four things is returned: (args, varargs, varkw, defaults).
'args' is a list of the argument names (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'defaults' is an n-tuple of the default values of the last n arguments.
"""
if ismethod(func):
func = func.__func__
if not isfunction(func):
raise TypeError('arg is not a Python function')
args, varargs, varkw = getargs(func.__code__)
return args, varargs, varkw, func.__defaults__
示例9: getargvalues
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargs [as 別名]
def getargvalues(frame):
"""Get information about arguments passed into a particular frame.
A tuple of four things is returned: (args, varargs, varkw, locals).
'args' is a list of the argument names (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'locals' is the locals dictionary of the given frame."""
args, varargs, varkw = getargs(frame.f_code)
return args, varargs, varkw, frame.f_locals
示例10: from_code
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargs [as 別名]
def from_code(cls, code, copy_lineno=False):
import inspect
self = cls.from_spec(code.co_name, *inspect.getargs(code))
if copy_lineno:
self.set_lineno(code.co_firstlineno)
self.co_filename = code.co_filename
self.co_freevars = code.co_freevars # XXX untested!
return self
示例11: call_function_with_correct_args
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargs [as 別名]
def call_function_with_correct_args(fn, **provided_kwargs):
# type: (Callable, Dict[str, Any]) -> Any
"""
Determines which arguments from **provided_kwargs** to call **fn** and calls it.
Consumes a list of allowed arguments (e.g. from :func:`~inspect.getargs()`) and
uses it to determine which of the arguments in the provided kwargs should be passed
through to the given callable.
:param Callable fn: A callable which has some dynamic arguments
:param List[str] allowed_args: A list of allowed arguments which can be passed to
the supplied function
:return: The result of calling the function
:rtype: Any
"""
# signature = inspect.signature(fn)
args = []
kwargs = {}
func_args, func_kwargs = get_allowed_args(fn)
for arg in func_args:
args.append(provided_kwargs[arg])
for arg in func_kwargs:
if not provided_kwargs.get(arg):
continue
kwargs[arg] = provided_kwargs[arg]
return fn(*args, **kwargs)
示例12: _parse_provides_dict
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargs [as 別名]
def _parse_provides_dict(
cls,
provides, # type: Dict[str, Callable]
prepend_arg_to_callables=None, # type: Optional[str]
):
# type: (...) -> Dict[str, Callable]
creating_methods = False
creating_classmethods = False
if prepend_arg_to_callables is not None:
if prepend_arg_to_callables == "self":
creating_methods = True
elif prepend_arg_to_callables == "cls":
creating_classmethods = True
provides_map = {}
for item_name, item_value in provides.items():
if isinstance(item_value, ShimmedPath):
item_value = item_value.shim()
if inspect.isfunction(item_value):
callable_args = inspect.getargs(item_value.__code__).args
if "self" not in callable_args and creating_methods:
item_value = make_method(item_value)(item_name)
elif "cls" not in callable_args and creating_classmethods:
item_value = make_classmethod(item_value)(item_name)
elif isinstance(item_value, six.string_types):
module_path, name = split_package(item_value)
module = cls._import_module(module_path)
item_value = getattr(module, name, None)
if item_value is not None:
provides_map[item_name] = item_value
return provides_map
示例13: _get_feature_funcs
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargs [as 別名]
def _get_feature_funcs(sfreq, module_name):
"""Inspection for feature functions.
Inspects a given module and returns a dictionary of feature
functions in this module. If the module does not contain any feature
function, an empty dictionary is returned.
Parameters
----------
sfreq : float
Sampling rate of the data.
module_name : str
Name of the module to inspect.
Returns
-------
feature_funcs : dict
"""
feature_funcs = dict()
res = getmembers(sys.modules[module_name], isfunction)
for name, func in res:
if name.startswith('compute_'):
alias = name.split('compute_')[-1]
if hasattr(func, 'func_code'):
func_code = func.func_code
else:
func_code = func.__code__
args, _, _ = getargs(func_code)
if 'sfreq' in args[0]:
feature_funcs[alias] = partial(func, sfreq)
else:
feature_funcs[alias] = func
return feature_funcs
示例14: get_params
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargs [as 別名]
def get_params(self, deep=True):
"""Get the parameters (if any) of the given feature function.
Parameters
----------
deep : bool (default: True)
If True, the method will get the parameters of the transformer.
(See :class:`~sklearn.preprocessing.FunctionTransformer`).
"""
func_to_inspect = _get_python_func(self.func)
# Get code object from the function
if hasattr(func_to_inspect, 'func_code'):
func_code = func_to_inspect.func_code
else:
func_code = func_to_inspect.__code__
args, _, _ = getargs(func_code)
# Get defaults from the function
if hasattr(func_to_inspect, 'defaults'):
defaults = func_to_inspect.func_defaults
else:
defaults = func_to_inspect.__defaults__
if defaults is None:
return dict()
else:
n_defaults = len(defaults)
func_params = {key: value for key, value in
zip(args[-n_defaults:], defaults)}
if self.params is not None:
func_params.update(self.params)
return func_params
示例15: exception_handler
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargs [as 別名]
def exception_handler(e):
tb = get_current_traceback()
last_frame = tb.frames[-1]
last_frame_args = inspect.getargs(last_frame.code)
return render_template('show_error.html',
tb=tb,
last_frame=last_frame,
last_frame_args=last_frame_args), 500