本文整理匯總了Python中inspect.formatargspec方法的典型用法代碼示例。如果您正苦於以下問題:Python inspect.formatargspec方法的具體用法?Python inspect.formatargspec怎麽用?Python inspect.formatargspec使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類inspect
的用法示例。
在下文中一共展示了inspect.formatargspec方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import formatargspec [as 別名]
def __init__(self, func, role='func', doc=None, config={}):
self._f = func
self._role = role # e.g. "func" or "meth"
if doc is None:
if func is None:
raise ValueError("No function or docstring given")
doc = inspect.getdoc(func) or ''
NumpyDocString.__init__(self, doc)
if not self['Signature'] and func is not None:
func, func_name = self.get_func()
try:
# try to read signature
argspec = inspect.getargspec(func)
argspec = inspect.formatargspec(*argspec)
argspec = argspec.replace('*', '\*')
signature = '%s%s' % (func_name, argspec)
except TypeError as e:
signature = '%s()' % func_name
self['Signature'] = signature
示例2: document_custom_signature
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import formatargspec [as 別名]
def document_custom_signature(section, name, method,
include=None, exclude=None):
"""Documents the signature of a custom method
:param section: The section to write the documentation to.
:param name: The name of the method
:param method: The handle to the method being documented
:type include: Dictionary where keys are parameter names and
values are the shapes of the parameter names.
:param include: The parameter shapes to include in the documentation.
:type exclude: List of the names of the parameters to exclude.
:param exclude: The names of the parameters to exclude from
documentation.
"""
args, varargs, keywords, defaults = inspect.getargspec(method)
args = args[1:]
signature_params = inspect.formatargspec(
args, varargs, keywords, defaults)
signature_params = signature_params.lstrip('(')
signature_params = signature_params.rstrip(')')
section.style.start_sphinx_py_method(name, signature_params)
示例3: make_wrapper
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import formatargspec [as 別名]
def make_wrapper(func, how):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
results = object.__getattribute__(self, '_results')
data = results.model.data
if how and isinstance(how, tuple):
obj = data.wrap_output(func(results, *args, **kwargs), how[0], how[1:])
elif how:
obj = data.wrap_output(func(results, *args, **kwargs), how)
return obj
argspec = getargspec(func)
formatted = inspect.formatargspec(argspec[0], varargs=argspec[1],
defaults=argspec[3])
func_name = get_function_name(func)
wrapper.__doc__ = "%s%s\n%s" % (func_name, formatted, wrapper.__doc__)
return wrapper
示例4: get_wrapped
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import formatargspec [as 別名]
def get_wrapped(func, wrapper_template, evaldict):
# Preserve the argspec for the wrapped function so that testing
# tools such as pytest can continue to use their fixture injection.
args, a, kw, defaults = inspect.getargspec(func)
values = args[-len(defaults):] if defaults else None
signature = inspect.formatargspec(args, a, kw, defaults)
is_bound_method = hasattr(func, '__self__')
if is_bound_method:
args = args[1:] # Omit 'self'
callargs = inspect.formatargspec(args, a, kw, values,
formatvalue=lambda v: '=' + v)
ctx = {'signature': signature, 'funcargs': callargs}
six.exec_(wrapper_template % ctx, evaldict)
wrapper = evaldict['wrapper']
update_wrapper(wrapper, func)
if is_bound_method:
wrapper = wrapper.__get__(func.__self__, type(func.__self__))
return wrapper
示例5: format_signature
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import formatargspec [as 別名]
def format_signature(func, *args, **kwargs):
# XXX: Should this use inspect.formatargvalues/formatargspec?
module, name = get_func_name(func)
module = [m for m in module if m]
if module:
module.append(name)
module_path = '.'.join(module)
else:
module_path = name
arg_str = list()
previous_length = 0
for arg in args:
formatted_arg = _format_arg(arg)
if previous_length > 80:
formatted_arg = '\n%s' % formatted_arg
previous_length = len(formatted_arg)
arg_str.append(formatted_arg)
arg_str.extend(['%s=%s' % (v, _format_arg(i)) for v, i in kwargs.items()])
arg_str = ', '.join(arg_str)
signature = '%s(%s)' % (name, arg_str)
return module_path, signature
示例6: formatargspec
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import formatargspec [as 別名]
def formatargspec(args, varargs=None, varkw=None, defaults=None,
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value),
join=joinseq):
"""Format an argument spec from the 4 values returned by getargspec.
The first four arguments are (args, varargs, varkw, defaults). The
other four arguments are the corresponding optional formatting functions
that are called to turn names and values into strings. The ninth
argument is an optional function to format the sequence of arguments."""
specs = []
if defaults:
firstdefault = len(args) - len(defaults)
for i in range(len(args)):
spec = strseq(args[i], formatarg, join)
if defaults and i >= firstdefault:
spec = spec + formatvalue(defaults[i - firstdefault])
specs.append(spec)
if varargs is not None:
specs.append(formatvarargs(varargs))
if varkw is not None:
specs.append(formatvarkw(varkw))
return '(' + ', '.join(specs) + ')'
示例7: __init__
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import formatargspec [as 別名]
def __init__(self, func, role='func', doc=None, config={}):
self._f = func
self._role = role # e.g. "func" or "meth"
if doc is None:
if func is None:
raise ValueError("No function or docstring given")
doc = inspect.getdoc(func) or ''
NumpyDocString.__init__(self, doc)
if not self['Signature'] and func is not None:
func, func_name = self.get_func()
try:
# try to read signature
if sys.version_info[0] >= 3:
argspec = inspect.getfullargspec(func)
else:
argspec = inspect.getargspec(func)
argspec = inspect.formatargspec(*argspec)
argspec = argspec.replace('*','\*')
signature = '%s%s' % (func_name, argspec)
except TypeError as e:
signature = '%s()' % func_name
self['Signature'] = signature
示例8: __init__
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import formatargspec [as 別名]
def __init__(self, func, role='func', doc=None, config={}):
self._f = func
self._role = role # e.g. "func" or "meth"
if doc is None:
if func is None:
raise ValueError("No function or docstring given")
doc = inspect.getdoc(func) or ''
NumpyDocString.__init__(self, doc)
if not self['Signature'] and func is not None:
func, func_name = self.get_func()
try:
# try to read signature
if sys.version_info[0] >= 3:
argspec = inspect.getfullargspec(func)
else:
argspec = inspect.getargspec(func)
argspec = inspect.formatargspec(*argspec)
argspec = argspec.replace('*', '\*')
signature = '%s%s' % (func_name, argspec)
except TypeError as e:
signature = '%s()' % func_name
self['Signature'] = signature
示例9: __init__
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import formatargspec [as 別名]
def __init__(self, func, role='func', doc=None, config={}):
self._f = func
self._role = role # e.g. "func" or "meth"
if doc is None:
if func is None:
raise ValueError("No function or docstring given")
doc = inspect.getdoc(func) or ''
NumpyDocString.__init__(self, doc)
if not self['Signature'] and func is not None:
func, func_name = self.get_func()
try:
# try to read signature
argspec = inspect.signature(func)
argspec = inspect.formatargspec(*argspec)
argspec = argspec.replace('*', '\*')
signature = '%s%s' % (func_name, argspec)
except TypeError as e:
signature = '%s()' % func_name
self['Signature'] = signature
示例10: assertFullArgSpecEquals
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import formatargspec [as 別名]
def assertFullArgSpecEquals(self, routine, args_e, varargs_e=None,
varkw_e=None, defaults_e=None,
kwonlyargs_e=[], kwonlydefaults_e=None,
ann_e={}, formatted=None):
args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
inspect.getfullargspec(routine)
self.assertEqual(args, args_e)
self.assertEqual(varargs, varargs_e)
self.assertEqual(varkw, varkw_e)
self.assertEqual(defaults, defaults_e)
self.assertEqual(kwonlyargs, kwonlyargs_e)
self.assertEqual(kwonlydefaults, kwonlydefaults_e)
self.assertEqual(ann, ann_e)
if formatted is not None:
self.assertEqual(inspect.formatargspec(args, varargs, varkw, defaults,
kwonlyargs, kwonlydefaults, ann),
formatted)
示例11: update_docstring
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import formatargspec [as 別名]
def update_docstring(dispatcher, func=None):
"""
Inserts a call signature at the beginning of the docstring on `dispatcher`.
The signature is taken from `func` if provided; otherwise `(...)` is used.
"""
doc = dispatcher.__doc__ or ''
if inspect.cleandoc(doc).startswith('%s(' % dispatcher.__name__):
return
sig = '(...)'
if func and func.__code__.co_argcount:
argspec = inspect.getfullargspec(func) # pylint: disable=deprecated-method
if argspec.args and argspec.args[0] in {'self', 'cls'}:
argspec.args.pop(0)
if any(argspec):
sig = inspect.formatargspec(*argspec) # pylint: disable=deprecated-method
sig = re.sub(r' at 0x[0-9a-f]{8,16}(?=>)', '', sig)
sep = '\n' if doc.startswith('\n') else '\n\n'
dispatcher.__doc__ = dispatcher.__name__ + sig + sep + doc
示例12: __init__
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import formatargspec [as 別名]
def __init__(self, func, role='func', doc=None, config={}):
self._f = func
self._role = role # e.g. "func" or "meth"
if doc is None:
if func is None:
raise ValueError("No function or docstring given")
doc = inspect.getdoc(func) or ''
NumpyDocString.__init__(self, doc)
if not self['Signature'] and func is not None:
func, func_name = self.get_func()
try:
# try to read signature
argspec = inspect.getargspec(func)
argspec = inspect.formatargspec(*argspec)
argspec = argspec.replace('*', '\*')
signature = '%s%s' % (func_name, argspec)
except TypeError, e:
signature = '%s()' % func_name
self['Signature'] = signature
示例13: __str__
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import formatargspec [as 別名]
def __str__(self):
out = ''
doclines = inspect.getdoc(self._f) or ''
try:
doc = SphinxDocString(doclines)
except Exception as e:
print('*' * 78)
print("ERROR: '%s' while parsing `%s`" % (e, self._f))
print('*' * 78)
# print "Docstring follows:"
# print doclines
# print '='*78
return out
if doc['Signature']:
out += '%s\n' % header('**%s**' %
doc['Signature'].replace('*', '\\*'), '-')
else:
try:
# try to read signature
argspec = inspect.getargspec(self._f)
argspec = inspect.formatargspec(*argspec)
argspec = argspec.replace('*', '\\*')
out += header('%s%s' % (self._f.__name__, argspec), '-')
except TypeError as e:
out += '%s\n' % header('**%s()**' % self._f.__name__, '-')
out += str(doc)
return out
示例14: _getsignature
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import formatargspec [as 別名]
def _getsignature(func, skipfirst, instance=False):
if isinstance(func, type) and not instance:
try:
func = func.__init__
except AttributeError:
return
skipfirst = True
elif not isinstance(func, FunctionTypes):
# for classes where instance is True we end up here too
try:
func = func.__call__
except AttributeError:
return
try:
argspec = inspect.getfullargspec(func)
except TypeError:
# C function / method, possibly inherited object().__init__
return
regargs, varargs, varkw, defaults, kwonly, kwonlydef, ann = argspec
# instance methods and classmethods need to lose the self argument
if getattr(func, '__self__', None) is not None:
regargs = regargs[1:]
if skipfirst:
# this condition and the above one are never both True - why?
regargs = regargs[1:]
signature = inspect.formatargspec(
regargs, varargs, varkw, defaults,
kwonly, kwonlydef, ann, formatvalue=lambda value: "")
return signature[1:-1], func
示例15: usage
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import formatargspec [as 別名]
def usage(obj, selfname='self'):
import inspect
str(obj) # In case it's lazy, this will load it.
if not isinstance(obj, class_types):
obj = obj.__class__
print('%s supports the following operations:' % obj.__name__)
for (name, method) in sorted(pydoc.allmethods(obj).items()):
if name.startswith('_'): continue
if getattr(method, '__deprecated__', False): continue
args, varargs, varkw, defaults = inspect.getargspec(method)
if (args and args[0]=='self' and
(defaults is None or len(args)>len(defaults))):
args = args[1:]
name = '%s.%s' % (selfname, name)
argspec = inspect.formatargspec(
args, varargs, varkw, defaults)
print(textwrap.fill('%s%s' % (name, argspec),
initial_indent=' - ',
subsequent_indent=' '*(len(name)+5)))
##########################################################################
# IDLE
##########################################################################