Python inspect 模块,formatargspec() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用inspect.formatargspec()

项目:code    作者:ActiveState    | 项目源码 | 文件源码
def enableAttributes(genfunc):
    """Wrapper for generators to enable classlike attribute access.

    The generator definition should specify 'self' as the first parameter.
    Calls to a wrapped generator should ignore the self parameter.
    """
    old = getargspec(genfunc)
    old[0].pop(0)
    new = getargspec(genfunc)
    new[0][0] = 'wrapped'
    specs = {'name': genfunc.func_name,
         'oldargs': formatargspec(*old),
         'newargs': formatargspec(*new)}
    exec(_redefinition % specs, genfunc.func_globals)


#### A minimal, complete example
项目:palladio    作者:slipguru    | 项目源码 | 文件源码
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
项目:skutil    作者:tgsmith61591    | 项目源码 | 文件源码
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
项目:aws-cfn-plex    作者:lordmuffin    | 项目源码 | 文件源码
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)
项目:RPoint    作者:george17-meet    | 项目源码 | 文件源码
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)

    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, None)

    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
项目:AshsSDK    作者:thehappydinoa    | 项目源码 | 文件源码
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)
项目:tflearn    作者:tflearn    | 项目源码 | 文件源码
def get_func_doc(name, func):
    doc_source = ''
    if name in SKIP:
        return  ''
    if name[0] == '_':
        return ''
    if func in classes_and_functions:
        return ''
    classes_and_functions.add(func)
    header = name + inspect.formatargspec(*inspect.getargspec(func))
    docstring = format_func_doc(inspect.getdoc(func), module_name + '.' +
                                header)

    if docstring != '':
        doc_source += docstring
        doc_source += '\n\n ---------- \n\n'

    return doc_source
项目:tflearn    作者:tflearn    | 项目源码 | 文件源码
def get_method_doc(name, func):
    doc_source = ''
    if name in SKIP:
        return  ''
    if name[0] == '_':
        return ''
    if func in classes_and_functions:
        return ''
    classes_and_functions.add(func)
    header = name + inspect.formatargspec(*inspect.getargspec(func))
    docstring = format_method_doc(inspect.getdoc(func), header)

    if docstring != '':
        doc_source += '\n\n <span class="hr_large"></span> \n\n'
        doc_source += docstring

    return doc_source
项目:noisyopt    作者:andim    | 项目源码 | 文件源码
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
项目:l1l2py    作者:slipguru    | 项目源码 | 文件源码
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
项目:bolero    作者:rock-learning    | 项目源码 | 文件源码
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
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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)
项目:pytypes    作者:Stewori    | 项目源码 | 文件源码
def getargnames(argspecs, with_unbox=False):
    """Resembles list of arg-names as would be seen in a function signature, including
    var-args, var-keywords and keyword-only args.
    """
    # todo: We can maybe make use of inspect.formatargspec
    args = argspecs.args
    vargs = argspecs.varargs
    try:
        kw = argspecs.keywords
    except AttributeError:
        kw = argspecs.varkw
    try:
        kwonly = argspecs.kwonlyargs
    except AttributeError:
        kwonly = None
    res = []
    if not args is None:
        res.extend(args)
    if not vargs is None:
        res.append('*'+vargs if with_unbox else vargs)
    if not kwonly is None:
        res.extend(kwonly)
    if not kw is None:
        res.append('**'+kw if with_unbox else kw)
    return res
项目:aws-ec2rescue-linux    作者:awslabs    | 项目源码 | 文件源码
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)
项目:dalila    作者:slipguru    | 项目源码 | 文件源码
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
项目:intel-manager-for-lustre    作者:intel-hpdd    | 项目源码 | 文件源码
def raw_result(wrapped):
    """
    Decorator for functions whose output should not be JSON-serialized.
    """
    def wrapper(*args, **kwargs):
        result = wrapped(*args, **kwargs)
        return {'raw_result': result}

    # These contortions are necessary to retain compatibility with
    # argparse's ability to generate CLI options by signature inspection.
    import functools
    wrapped_signature = inspect.getargspec(wrapped)
    formatted_args = inspect.formatargspec(*wrapped_signature)
    compat_name = "_%s" % wrapped.func_name
    compat_def = 'lambda %s: %s%s' % (formatted_args.lstrip('(').rstrip(')'),
                                      compat_name, formatted_args)
    compat_fn = eval(compat_def, {compat_name: wrapper})
    return functools.wraps(wrapped)(compat_fn)
项目:dyfunconn    作者:makism    | 项目源码 | 文件源码
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
项目:dask-searchcv    作者:dask    | 项目源码 | 文件源码
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
项目:chalktalk_docs    作者:loremIpsum1771    | 项目源码 | 文件源码
def format_args(self):
        if inspect.isbuiltin(self.object) or \
                inspect.ismethoddescriptor(self.object):
            # cannot introspect arguments of a C function or method
            return None
        try:
            argspec = getargspec(self.object)
        except TypeError:
            if (is_builtin_class_method(self.object, '__new__') and
               is_builtin_class_method(self.object, '__init__')):
                raise TypeError('%r is a builtin class' % self.object)

            # if a class should be documented as function (yay duck
            # typing) we try to use the constructor signature as function
            # signature without the first argument.
            try:
                argspec = getargspec(self.object.__new__)
            except TypeError:
                argspec = getargspec(self.object.__init__)
                if argspec[0]:
                    del argspec[0][0]
        args = formatargspec(*argspec)
        # escape backslashes for reST
        args = args.replace('\\', '\\\\')
        return args
项目:chalktalk_docs    作者:loremIpsum1771    | 项目源码 | 文件源码
def format_args(self):
        # for classes, the relevant signature is the __init__ method's
        initmeth = self.get_attr(self.object, '__init__', None)
        # classes without __init__ method, default __init__ or
        # __init__ written in C?
        if initmeth is None or \
                is_builtin_class_method(self.object, '__init__') or \
                not(inspect.ismethod(initmeth) or inspect.isfunction(initmeth)):
            return None
        try:
            argspec = getargspec(initmeth)
        except TypeError:
            # still not possible: happens e.g. for old-style classes
            # with __init__ in C
            return None
        if argspec[0] and argspec[0][0] in ('cls', 'self'):
            del argspec[0][0]
        return formatargspec(*argspec)
项目:tefla    作者:openAGI    | 项目源码 | 文件源码
def get_func_doc(name, func):
    doc_source = ''
    if name in SKIP:
        return ''
    # if name[0] == '_':
    #    return ''
    if func in classes_and_functions:
        return ''
    classes_and_functions.add(func)
    header = name + inspect.formatargspec(*inspect.getargspec(func))
    path = get_src_path(func)
    # FUNC_TEMP = "[{header}]({path})"
    # header = FUNC_TEMP.format(header=header, path=path)
    # print(header)
    docstring = format_func_doc(inspect.getdoc(func), module_name + '.' +
                                header, path)
    print(docstring)

    if docstring != '':
        doc_source += docstring
        doc_source += '\n\n ---------- \n\n'

    return doc_source
项目:tefla    作者:openAGI    | 项目源码 | 文件源码
def get_method_doc(name, func):
    doc_source = ''
    if name in SKIP:
        return ''
    if name[0] == '_':
        return ''
    if func in classes_and_functions:
        return ''
    classes_and_functions.add(func)
    header = name + inspect.formatargspec(*inspect.getargspec(func))
    path = get_src_path(func)
    docstring = format_method_doc(inspect.getdoc(func), header, path)

    if docstring != '':
        doc_source += '\n\n <span class="hr_large"></span> \n\n'
        doc_source += docstring

    return doc_source
项目:PyShearlets    作者:grlee77    | 项目源码 | 文件源码
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
项目:icing    作者:slipguru    | 项目源码 | 文件源码
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
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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)
项目:polylearn    作者:scikit-learn-contrib    | 项目源码 | 文件源码
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
项目:python-pulse-control    作者:mk-fg    | 项目源码 | 文件源码
def _pulse_method_call(pulse_op, func=None, index_arg=True):
        '''Creates following synchronous wrapper for async pa_operation callable:
            wrapper(index, ...) -> pulse_op(index, [*]args_func(...))
            index_arg=False: wrapper(...) -> pulse_op([*]args_func(...))'''
        def _wrapper(self, *args, **kws):
            if index_arg:
                if 'index' in kws: index = kws.pop('index')
                else: index, args = args[0], args[1:]
            pulse_args = func(*args, **kws) if func else list()
            if not is_list(pulse_args): pulse_args = [pulse_args]
            if index_arg: pulse_args = [index] + list(pulse_args)
            with self._pulse_op_cb() as cb:
                try: pulse_op(self._ctx, *(list(pulse_args) + [cb, None]))
                except c.ArgumentError as err: raise TypeError(err.args)
                except c.pa.CallError as err: raise PulseOperationInvalid(err.args[-1])
        func_args = list(inspect.getargspec(func or (lambda: None)))
        func_args[0] = list(func_args[0])
        if index_arg: func_args[0] = ['index'] + func_args[0]
        _wrapper.__name__ = '...'
        _wrapper.__doc__ = 'Signature: func' + inspect.formatargspec(*func_args)
        if func.__doc__: _wrapper.__doc__ += '\n\n' + func.__doc__
        return _wrapper
项目:python-gnutls    作者:AGProjects    | 项目源码 | 文件源码
def preserve_signature(func):
    """Preserve the original function signature and attributes in decorator wrappers."""
    from inspect import getargspec, formatargspec
    from gnutls.constants import GNUTLSConstant
    constants  = [c for c in (getargspec(func)[3] or []) if isinstance(c, GNUTLSConstant)]
    signature  = formatargspec(*getargspec(func))[1:-1]
    parameters = formatargspec(*getargspec(func), **{'formatvalue': lambda value: ""})[1:-1]
    def fix_signature(wrapper):
        if constants:
            ## import the required GNUTLSConstants used as function default arguments
            code = "from gnutls.constants import %s\n" % ', '.join(c.name for c in constants)
            exec code in locals(), locals()
        code = "def %s(%s): return wrapper(%s)\nnew_wrapper = %s\n" % (func.__name__, signature, parameters, func.__name__)
        exec code in locals(), locals()
        new_wrapper.__name__ = func.__name__
        new_wrapper.__doc__ = func.__doc__
        new_wrapper.__module__ = func.__module__
        new_wrapper.__dict__.update(func.__dict__)
        return new_wrapper
    return fix_signature

# Argument validating decorators
#
项目:AmqpCode    作者:SVADemoAPP    | 项目源码 | 文件源码
def synchronized(meth):
  args, vargs, kwargs, defs = inspect.getargspec(meth)
  scope = {}
  scope["meth"] = meth
  exec """
def %s%s:
  %s
  %s._lock.acquire()
  try:
    return meth%s
  finally:
    %s._lock.release()
""" % (meth.__name__, inspect.formatargspec(args, vargs, kwargs, defs),
       repr(inspect.getdoc(meth)), args[0],
       inspect.formatargspec(args, vargs, kwargs, defs,
                             formatvalue=lambda x: ""),
       args[0]) in scope
  return scope[meth.__name__]
项目:mlens    作者:flennerhag    | 项目源码 | 文件源码
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
项目:qpid-python    作者:apache    | 项目源码 | 文件源码
def synchronized(meth):
  args, vargs, kwargs, defs = inspect.getargspec(meth)
  scope = {}
  scope["meth"] = meth
  exec """
def %s%s:
  %s
  %s._lock.acquire()
  try:
    return meth%s
  finally:
    %s._lock.release()
""" % (meth.__name__, inspect.formatargspec(args, vargs, kwargs, defs),
       repr(inspect.getdoc(meth)), args[0],
       inspect.formatargspec(args, vargs, kwargs, defs,
                             formatvalue=lambda x: ""),
       args[0]) in scope
  return scope[meth.__name__]
项目:reahl    作者:reahl    | 项目源码 | 文件源码
def signatures_match(cls, orig, stubbed, ignore_self=False):
        if six.PY2:
            orig_arguments = inspect.getargspec(orig)
            stub_arguments = inspect.getargspec(stubbed)
        else:
            orig_arguments = inspect.getfullargspec(orig)
            stub_arguments = inspect.getfullargspec(stubbed)

        if ignore_self:
            if 'self' in orig_arguments.args: orig_arguments.args.remove('self')
            if 'self' in stub_arguments.args: stub_arguments.args.remove('self')
        assert orig_arguments == stub_arguments, \
            'signature mismatch: %s%s does not match %s%s' % \
            (stubbed, inspect.formatargspec(*stub_arguments), 
             orig, inspect.formatargspec(*orig_arguments))

        return False



#------------------------------------------------[ Impostor ]
项目:kscore    作者:liuyichen    | 项目源码 | 文件源码
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)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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)
项目:jepsen-training-vpc    作者:bloomberg    | 项目源码 | 文件源码
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)
项目:rankpy    作者:dmitru    | 项目源码 | 文件源码
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:
        arg = pformat(arg, indent=2)
        if len(arg) > 1500:
            arg = '%s...' % arg[:700]
        if previous_length > 80:
            arg = '\n%s' % arg
        previous_length = len(arg)
        arg_str.append(arg)
    arg_str.extend(['%s=%s' % (v, pformat(i)) for v, i in kwargs.items()])
    arg_str = ', '.join(arg_str)

    signature = '%s(%s)' % (name, arg_str)
    return module_path, signature
项目:AWS-AutoTag    作者:cpollard0    | 项目源码 | 文件源码
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)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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)
项目:niworkflows    作者:poldracklab    | 项目源码 | 文件源码
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
项目:xrft    作者:rabernat    | 项目源码 | 文件源码
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
项目:core-framework    作者:RedhawkSDR    | 项目源码 | 文件源码
def _notification_signature(func):
    # To provide meaningful documentation of the signature of a
    # notification, inspect the wrapped function to get its arguments.
    args, varargs, varkw, defaults = inspect.getargspec(func)
    if len(args) > 0 and args[0] == 'self':
        # Discard "self" argument, if it exists.
        args = args[1:]
    return func.__name__+inspect.formatargspec(args, varargs, varkw, defaults)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def docroutine(self, object, name, mod=None,
                   funcs={}, classes={}, methods={}, cl=None):
        """Produce HTML documentation for a function or method object."""

        anchor = (cl and cl.__name__ or '') + '-' + name
        note = ''

        title = '<a name="%s"><strong>%s</strong></a>' % (
            self.escape(anchor), self.escape(name))

        if inspect.ismethod(object):
            args, varargs, varkw, defaults = inspect.getargspec(object.im_func)
            # exclude the argument bound to the instance, it will be
            # confusing to the non-Python user
            argspec = inspect.formatargspec (
                    args[1:],
                    varargs,
                    varkw,
                    defaults,
                    formatvalue=self.formatvalue
                )
        elif inspect.isfunction(object):
            args, varargs, varkw, defaults = inspect.getargspec(object)
            argspec = inspect.formatargspec(
                args, varargs, varkw, defaults, formatvalue=self.formatvalue)
        else:
            argspec = '(...)'

        if isinstance(object, tuple):
            argspec = object[0] or argspec
            docstring = object[1] or ""
        else:
            docstring = pydoc.getdoc(object)

        decl = title + argspec + (note and self.grey(
               '<font face="helvetica, arial">%s</font>' % note))

        doc = self.markup(
            docstring, self.preformat, funcs, classes, methods)
        doc = doc and '<dd><tt>%s</tt></dd>' % doc
        return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
def monkeypatch_proxied_specials(into_cls, from_cls, skip=None, only=None,
                                 name='self.proxy', from_instance=None):
    """Automates delegation of __specials__ for a proxying type."""

    if only:
        dunders = only
    else:
        if skip is None:
            skip = ('__slots__', '__del__', '__getattribute__',
                    '__metaclass__', '__getstate__', '__setstate__')
        dunders = [m for m in dir(from_cls)
                   if (m.startswith('__') and m.endswith('__') and
                       not hasattr(into_cls, m) and m not in skip)]

    for method in dunders:
        try:
            fn = getattr(from_cls, method)
            if not hasattr(fn, '__call__'):
                continue
            fn = getattr(fn, 'im_func', fn)
        except AttributeError:
            continue
        try:
            spec = compat.inspect_getargspec(fn)
            fn_args = inspect.formatargspec(spec[0])
            d_args = inspect.formatargspec(spec[0][1:])
        except TypeError:
            fn_args = '(self, *args, **kw)'
            d_args = '(*args, **kw)'

        py = ("def %(method)s%(fn_args)s: "
              "return %(name)s.%(method)s%(d_args)s" % locals())

        env = from_instance is not None and {name: from_instance} or {}
        compat.exec_(py, env)
        try:
            env[method].__defaults__ = fn.__defaults__
        except AttributeError:
            pass
        setattr(into_cls, method, env[method])
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _format_args(func):
        return inspect.formatargspec(*inspect.getargspec(func))
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _formatdef(func):
        return "%s%s" % (
            func.__name__,
            inspect.formatargspec(*inspect.getargspec(func))
        )
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def docroutine(self, object, name, mod=None,
                   funcs={}, classes={}, methods={}, cl=None):
        """Produce HTML documentation for a function or method object."""

        anchor = (cl and cl.__name__ or '') + '-' + name
        note = ''

        title = '<a name="%s"><strong>%s</strong></a>' % (
            self.escape(anchor), self.escape(name))

        if inspect.ismethod(object):
            args, varargs, varkw, defaults = inspect.getargspec(object.im_func)
            # exclude the argument bound to the instance, it will be
            # confusing to the non-Python user
            argspec = inspect.formatargspec (
                    args[1:],
                    varargs,
                    varkw,
                    defaults,
                    formatvalue=self.formatvalue
                )
        elif inspect.isfunction(object):
            args, varargs, varkw, defaults = inspect.getargspec(object)
            argspec = inspect.formatargspec(
                args, varargs, varkw, defaults, formatvalue=self.formatvalue)
        else:
            argspec = '(...)'

        if isinstance(object, tuple):
            argspec = object[0] or argspec
            docstring = object[1] or ""
        else:
            docstring = pydoc.getdoc(object)

        decl = title + argspec + (note and self.grey(
               '<font face="helvetica, arial">%s</font>' % note))

        doc = self.markup(
            docstring, self.preformat, funcs, classes, methods)
        doc = doc and '<dd><tt>%s</tt></dd>' % doc
        return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
项目:python-application    作者:AGProjects    | 项目源码 | 文件源码
def preserve_signature(func):
    """Preserve the original function signature and attributes in decorator wrappers."""
    def fix_signature(wrapper):
        exec_scope = {}
        parameters = formatargspec(*getargspec(func), formatvalue=lambda value: "")
        exec "def {0}{1}: return wrapper{1}".format(func.__name__, parameters) in {'wrapper': wrapper}, exec_scope  # can't use tuple form here (see https://bugs.python.org/issue21591)
        new_wrapper = exec_scope.pop(func.__name__)
        new_wrapper.__name__ = func.__name__
        new_wrapper.__doc__ = func.__doc__
        new_wrapper.__module__ = func.__module__
        new_wrapper.__defaults__ = func.__defaults__
        new_wrapper.__dict__.update(func.__dict__)
        return new_wrapper
    return fix_signature
项目:pyuf    作者:uArm-Developer    | 项目源码 | 文件源码
def docroutine(self, object, name=None, mod=None, cl=None):
        """Produce text documentation for a function or method object."""
        realname = object.__name__
        name = name or realname
        note = ''
        skipdocs = 0
        if inspect.ismethod(object):
            object = object.__func__
        if name == realname:
            title = self.bold(realname)
        else:
            if (cl and realname in cl.__dict__ and cl.__dict__[realname] is object):
                skipdocs = 1
            title = self.bold(name) + ' = ' + realname
        if inspect.isfunction(object):
            args, varargs, varkw, defaults, kwonlyargs, kwdefaults, ann = inspect.getfullargspec(object)
            argspec = inspect.formatargspec(
                args, varargs, varkw, defaults, kwonlyargs, kwdefaults, ann,
                formatvalue=self.formatvalue,
                formatannotation=inspect.formatannotationrelativeto(object))
            if realname == '<lambda>':
                title = self.bold(name) + ' lambda '
                # XXX lambda's won't usually have func_annotations['return']
                # since the syntax doesn't support but it is possible.
                # So removing parentheses isn't truly safe.
                argspec = argspec[1:-1] # remove parentheses
        else:
            argspec = '(...)'
        decl = "#### " + "def " + title + argspec + ':' + '\n' + note

        if skipdocs:
            return decl + '\n'
        else:
            doc = pydoc.getdoc(object) or ''
            return decl + '\n' + (doc and self.indent(doc).rstrip() + '\n')
项目:cleverhans    作者:tensorflow    | 项目源码 | 文件源码
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