當前位置: 首頁>>代碼示例>>Python>>正文


Python inspect.ArgSpec方法代碼示例

本文整理匯總了Python中inspect.ArgSpec方法的典型用法代碼示例。如果您正苦於以下問題:Python inspect.ArgSpec方法的具體用法?Python inspect.ArgSpec怎麽用?Python inspect.ArgSpec使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在inspect的用法示例。


在下文中一共展示了inspect.ArgSpec方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _getargspec_py23

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import ArgSpec [as 別名]
def _getargspec_py23(func):
    """_getargspec_py23(function) -> named tuple ArgSpec(args, varargs, keywords,
                                                        defaults)

    Identical to inspect.getargspec() in python2, but uses
    inspect.getfullargspec() for python3 behind the scenes to avoid
    DeprecationWarning.

    >>> def f(a, b=2, *ar, **kw):
    ...     pass

    >>> _getargspec_py23(f)
    ArgSpec(args=['a', 'b'], varargs='ar', keywords='kw', defaults=(2,))
    """
    if six.PY2:
        return inspect.getargspec(func)

    return inspect.ArgSpec(*inspect.getfullargspec(func)[:4]) 
開發者ID:wistbean,項目名稱:learn_python3_spider,代碼行數:20,代碼來源:python.py

示例2: getargspec

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import ArgSpec [as 別名]
def getargspec(  # pylint: disable=inconsistent-return-statements
    fn
):  # type: (Callable) -> inspect.ArgSpec
    """Get the names and default values of a function's arguments.

    Args:
        fn (function): a function

    Returns:
        `inspect.ArgSpec`:  A collections.namedtuple with the following attributes:

            * Args:
                args (list): a list of the argument names (it may contain nested lists).
                varargs (str): name of the * argument or None.
                keywords (str): names of the ** argument or None.
                defaults (tuple): an n-tuple of the default values of the last n arguments.
    """
    if six.PY2:
        return inspect.getargspec(fn)  # pylint: disable=deprecated-method
    elif six.PY3:
        full_arg_spec = inspect.getfullargspec(fn)
        return inspect.ArgSpec(
            full_arg_spec.args, full_arg_spec.varargs, full_arg_spec.varkw, full_arg_spec.defaults
        ) 
開發者ID:aws,項目名稱:sagemaker-containers,代碼行數:26,代碼來源:_functions.py

示例3: getargspec

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import ArgSpec [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__) 
開發者ID:quora,項目名稱:qcore,代碼行數:21,代碼來源:inspection.py

示例4: test_getargspec

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import ArgSpec [as 別名]
def test_getargspec():
    empty = inspect.ArgSpec(args=[], varargs=None, keywords=None, defaults=None)
    assert_eq(empty, qcore.inspection.getargspec(test_get_subclass_tree))
    assert_eq(empty, qcore.inspection.getargspec(qcore.inspection.lazy_stack))

    emptymethod = inspect.ArgSpec(
        args=["self"], varargs=None, keywords=None, defaults=None
    )
    assert_eq(emptymethod, qcore.inspection.getargspec(X.myinstancemethod))
    assert_eq(emptymethod, qcore.inspection.getargspec(X().myinstancemethod))

    emptyclsmethod = inspect.ArgSpec(
        args=["cls"], varargs=None, keywords=None, defaults=None
    )
    assert_eq(emptyclsmethod, qcore.inspection.getargspec(X.myclassmethod))

    spec = inspect.ArgSpec(
        args=["a", "b", "c", "d"], varargs=None, keywords="f", defaults=("e",)
    )
    assert_eq(spec, qcore.inspection.getargspec(fun_with_args)) 
開發者ID:quora,項目名稱:qcore,代碼行數:22,代碼來源:test_inspection.py

示例5: getargspec

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import ArgSpec [as 別名]
def getargspec(object):  # pylint: disable=redefined-builtin
  """TFDecorator-aware replacement for inspect.getargspec.

  Args:
    object: A callable, possibly decorated.

  Returns:
    The `ArgSpec` that describes the signature of the outermost decorator that
    changes the callable's signature. If the callable is not decorated,
    `inspect.getargspec()` will be called directly on the callable.
  """
  decorators, target = tf_decorator.unwrap(object)
  return next((d.decorator_argspec for d in decorators
               if d.decorator_argspec is not None), _inspect.getargspec(target)) 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:16,代碼來源:tf_inspect.py

示例6: _passed

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import ArgSpec [as 別名]
def _passed(argspec, positional, keyword):
    """
    Take an I{inspect.ArgSpec}, a tuple of positional arguments, and a dict of
    keyword arguments, and return a mapping of arguments that were actually
    passed to their passed values.

    @param argspec: The argument specification for the function to inspect.
    @type argspec: I{inspect.ArgSpec}

    @param positional: The positional arguments that were passed.
    @type positional: L{tuple}

    @param keyword: The keyword arguments that were passed.
    @type keyword: L{dict}

    @return: A dictionary mapping argument names (those declared in C{argspec})
        to values that were passed explicitly by the user.
    @rtype: L{dict} mapping L{str} to L{object}
    """
    result = {}
    unpassed = len(argspec.args) - len(positional)
    if argspec.keywords is not None:
        kwargs = result[argspec.keywords] = {}
    if unpassed < 0:
        if argspec.varargs is None:
            raise TypeError("Too many arguments.")
        else:
            result[argspec.varargs] = positional[len(argspec.args):]
    for name, value in zip(argspec.args, positional):
        result[name] = value
    for name, value in keyword.items():
        if name in argspec.args:
            if name in result:
                raise TypeError("Already passed.")
            result[name] = value
        elif argspec.keywords is not None:
            kwargs[name] = value
        else:
            raise TypeError("no such param")
    return result 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:42,代碼來源:deprecate.py

示例7: _getargspec_init

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import ArgSpec [as 別名]
def _getargspec_init(method):
        try:
            return inspect.getargspec(method)
        except TypeError:
            if method is object.__init__:
                return ArgSpec(["self"], None, None, None)
            else:
                return ArgSpec(["self"], "args", "kwargs", None) 
開發者ID:thomaxxl,項目名稱:safrs,代碼行數:10,代碼來源:codegen.py

示例8: add_request_to_signature

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import ArgSpec [as 別名]
def add_request_to_signature(function):
    argspec = inspect.getargspec(function)
    return inspect.ArgSpec(argspec.args + ['request'], argspec.varargs, argspec.keywords, argspec.defaults) 
開發者ID:IvanMalison,項目名稱:okcupyd,代碼行數:5,代碼來源:util.py

示例9: _passedArgSpec

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import ArgSpec [as 別名]
def _passedArgSpec(argspec, positional, keyword):
    """
    Take an I{inspect.ArgSpec}, a tuple of positional arguments, and a dict of
    keyword arguments, and return a mapping of arguments that were actually
    passed to their passed values.

    @param argspec: The argument specification for the function to inspect.
    @type argspec: I{inspect.ArgSpec}

    @param positional: The positional arguments that were passed.
    @type positional: L{tuple}

    @param keyword: The keyword arguments that were passed.
    @type keyword: L{dict}

    @return: A dictionary mapping argument names (those declared in C{argspec})
        to values that were passed explicitly by the user.
    @rtype: L{dict} mapping L{str} to L{object}
    """
    result = {}
    unpassed = len(argspec.args) - len(positional)
    if argspec.keywords is not None:
        kwargs = result[argspec.keywords] = {}
    if unpassed < 0:
        if argspec.varargs is None:
            raise TypeError("Too many arguments.")
        else:
            result[argspec.varargs] = positional[len(argspec.args):]
    for name, value in zip(argspec.args, positional):
        result[name] = value
    for name, value in keyword.items():
        if name in argspec.args:
            if name in result:
                raise TypeError("Already passed.")
            result[name] = value
        elif argspec.keywords is not None:
            kwargs[name] = value
        else:
            raise TypeError("no such param")
    return result 
開發者ID:wistbean,項目名稱:learn_python3_spider,代碼行數:42,代碼來源:deprecate.py

示例10: get_default_args

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import ArgSpec [as 別名]
def get_default_args(o):
    """獲取函數的默認參數名-值映射
    """
    argspec = o
    if not isinstance(o, inspect.ArgSpec):
        argspec = inspect.getargspec(o)
    if not argspec.defaults:
        return {}
    return dict(zip(argspec.args[-len(argspec.defaults):],
                    argspec.defaults))

# 線性集合類型 
開發者ID:chihongze,項目名稱:girlfriend,代碼行數:14,代碼來源:lang.py

示例11: set_preprocess_fn

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import ArgSpec [as 別名]
def set_preprocess_fn(self, preprocess_fn):  # pytype: disable=invalid-annotation
    """Register the preprocess_fn used during the input data generation.

    Note, the preprocess_fn can only have `features` and optionally `labels` as
    inputs. The `mode` has to be abstracted by using a closure or
    functools.partial prior to passing a preprocessor.preprocess function.
    For example using functools:
    set_preprocess_fn(
      functools.partial(preprocessor.preprocess,
                        mode=tf.estimator.ModeKeys.TRAIN))

    Args:
      preprocess_fn: The function called during the input dataset generation to
        preprocess the data.
    """

    if isinstance(preprocess_fn, functools.partial):  # pytype: disable=wrong-arg-types
      # Note, we do not combine both conditions into one since
      # inspect.getargspec does not work for functools.partial objects.
      if 'mode' not in preprocess_fn.keywords:
        raise ValueError('The preprocess_fn mode has to be set if a partial'
                         'function has been passed.')
    else:
      if six.PY3:
        argspec = inspect.getfullargspec(preprocess_fn)
        # first 4 element of fullspec corresponds to spec:
        # https://docs.python.org/3.4/library/inspect.html
        argspec = inspect.ArgSpec(*argspec[:4])
      else:
        argspec = inspect.getargspec(preprocess_fn)  # pylint: disable=deprecated-method
      if 'mode' in argspec.args:
        raise ValueError('The passed preprocess_fn has an open argument `mode`'
                         'which should be patched by a closure or with '
                         'functools.partial.')

    self._preprocess_fn = preprocess_fn 
開發者ID:google-research,項目名稱:tensor2robot,代碼行數:38,代碼來源:abstract_input_generator.py

示例12: argspec

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import ArgSpec [as 別名]
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 = _getargspec(callable_obj.__call__)
        args = spec.args[1:]
    elif inspect.isfunction(callable_obj):    # functions and staticmethods
        spec = _getargspec(callable_obj)
        args = spec.args
    elif isinstance(callable_obj, partial): # partials
        arglen = len(callable_obj.args)
        spec =  _getargspec(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 = _getargspec(callable_obj)
        args = spec.args[1:]
    else:                                   # callable objects
        return argspec(callable_obj.__call__)

    return inspect.ArgSpec(args=args,
                           varargs=spec.varargs,
                           keywords=get_keywords(spec),
                           defaults=spec.defaults) 
開發者ID:holoviz,項目名稱:holoviews,代碼行數:33,代碼來源:util.py

示例13: noargs

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import ArgSpec [as 別名]
def noargs(self):
        "Returns True if the callable takes no arguments"
        noargs = inspect.ArgSpec(args=[], varargs=None, keywords=None, defaults=None)
        return self.argspec == noargs 
開發者ID:holoviz,項目名稱:holoviews,代碼行數:6,代碼來源:spaces.py

示例14: argspec

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import ArgSpec [as 別名]
def argspec(self):
        return inspect.ArgSpec(args=[], varargs=None, keywords=None, defaults=None) 
開發者ID:holoviz,項目名稱:holoviews,代碼行數:4,代碼來源:spaces.py

示例15: zip_arguments_defaults

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import ArgSpec [as 別名]
def zip_arguments_defaults(argspec):
    # type: (inspect.ArgSpec) -> Iterable
    if not argspec.defaults:
        return []

    return zip(
        argspec.args[-len(argspec.defaults):],
        argspec.defaults) 
開發者ID:botify-labs,項目名稱:simpleflow,代碼行數:10,代碼來源:execute.py


注:本文中的inspect.ArgSpec方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。