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


Python inspect.getargspec方法代碼示例

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


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

示例1: __init__

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargspec [as 別名]
def __init__(self, docstring, class_name, class_object):
        super(NumpyClassDocString, self).__init__(docstring)
        self.class_name = class_name
        methods = dict((name, func) for name, func
                       in inspect.getmembers(class_object))

        self.has_parameters = False
        if '__init__' in methods:
            # verify if __init__ is a Python function. If it isn't
            # (e.g. the function is implemented in C), getargspec will fail
            if not inspect.ismethod(methods['__init__']):
                return
            args, varargs, keywords, defaults = inspect.getargspec(
                methods['__init__'])
            if (args and args != ['self']) or varargs or keywords or defaults:
                self.has_parameters = True 
開發者ID:StephanZheng,項目名稱:neural-fingerprinting,代碼行數:18,代碼來源:docscrape.py

示例2: register_ranged_hparams

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargspec [as 別名]
def register_ranged_hparams(name=None):
  """Register a RangedHParams set. name defaults to fn name snake-cased."""

  def decorator(rhp_fn, registration_name=None):
    """Registers & returns hp_fn with registration_name or default name."""
    rhp_name = registration_name or default_name(rhp_fn)
    if rhp_name in _RANGED_HPARAMS:
      raise LookupError("RangedHParams set %s already registered." % rhp_name)
    # Check that the fn takes a single argument
    args, varargs, keywords, _ = inspect.getargspec(rhp_fn)
    if len(args) != 1 or varargs is not None or keywords is not None:
      raise ValueError("RangedHParams set function must take a single "
                       "argument, the RangedHParams object.")

    _RANGED_HPARAMS[rhp_name] = rhp_fn
    return rhp_fn

  # Handle if decorator was used without parens
  if callable(name):
    rhp_fn = name
    return decorator(rhp_fn, registration_name=default_name(rhp_fn))

  return lambda rhp_fn: decorator(rhp_fn, name) 
開發者ID:akzaidi,項目名稱:fine-lm,代碼行數:25,代碼來源:registry.py

示例3: oneshot

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargspec [as 別名]
def oneshot(equations, *args):
    """
    A one-shot calculation.
    Args:
        equations (callable): coupled-cluster equations;
        args (iterable): amplitudes and hamiltonian matrix elements as dicts;

    Returns:
        Results of the calculation.
    """
    input_args = inspect.getargspec(equations).args
    fw_args = {}
    for i in args:
        fw_args.update(i)
    # Remove excess arguments from the Hamiltonian
    fw_args = {k: v for k, v in fw_args.items() if k in input_args}
    # Check missing arguments
    missing = set(input_args) - set(fw_args.keys())
    if len(missing) > 0:
        raise ValueError("Following arguments are missing: {}".format(', '.join(missing)))
    return equations(**fw_args) 
開發者ID:pyscf,項目名稱:pyscf,代碼行數:23,代碼來源:pyscf_helpers.py

示例4: usage

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargspec [as 別名]
def usage(error=None):
    if error:
        print ("Error: " + error)
    print ("LGTV Controller")
    print ("Author: Karl Lattimer <karl@qdh.org.uk>")
    print ("Usage: lgtv <command> [parameter]\n")
    print ("Available Commands:")

    print ("  -i                    interactive mode")

    print ("  scan")
    print ("  auth <host> <tv_name>")

    commands = LGTVRemote.getCommands()
    for c in commands:
        args = getargspec(LGTVRemote.__dict__[c])
        if len(args.args) > 1:
            a = ' <' + '> <'.join(args.args[1:-1]) + '>'
            print ('  <tv_name> ' + c + a)
        else:
            print ('  <tv_name> ' + c) 
開發者ID:klattimer,項目名稱:LGWebOSRemote,代碼行數:23,代碼來源:__init__.py

示例5: parseargs

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargspec [as 別名]
def parseargs(command, argv):
    args = getargspec(LGTVRemote.__dict__[command])
    args = args.args[1:-1]

    if len(args) != len(argv):
        raise Exception("Argument lengths do not match")

    output = {}
    for (i, a) in enumerate(args):
        if argv[i].lower() == "true":
            argv[i] = True
        elif argv[i].lower() == "false":
            argv[i] = False
        try:
            f = int(argv[i])
            argv[i] = f
        except:
            try:
                f = float(argv[i])
                argv[i] = f
            except:
                pass
        output[a] = argv[i]
    return output 
開發者ID:klattimer,項目名稱:LGWebOSRemote,代碼行數:26,代碼來源:__init__.py

示例6: usage

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargspec [as 別名]
def usage(error=None):
    if error:
        print ("Error: " + error)
    print ("LGTV Controller")
    print ("Author: Karl Lattimer <karl@qdh.org.uk>")
    print ("Usage: lgtv <command> [parameter]\n")
    print ("Available Commands:")

    print ("  scan")
    print ("  auth                  Hostname/IP    Authenticate and exit, creates initial config ~/.lgtv.json")

    for c in getCommands(LGTVClient):
        print ("  " + c, end=" ")
        print (" " * (20 - len(c)), end=" ")
        args = getargspec(LGTVClient.__dict__[c])
        print (' '.join(args.args[1:-1])) 
開發者ID:klattimer,項目名稱:LGWebOSRemote,代碼行數:18,代碼來源:main.py

示例7: expects_func_args

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargspec [as 別名]
def expects_func_args(*args):
    def _decorator_checker(dec):
        @functools.wraps(dec)
        def _decorator(f):
            base_f = get_wrapped_function(f)
            argspec = getargspec(base_f)
            if argspec[1] or argspec[2] or set(args) <= set(argspec[0]):
                # NOTE (ndipanov): We can't really tell if correct stuff will
                # be passed if it's a function with *args or **kwargs so
                # we still carry on and hope for the best
                return dec(f)
            else:
                raise TypeError("Decorated function %(f_name)s does not "
                                "have the arguments expected by the "
                                "decorator %(d_name)s" %
                                {'f_name': base_f.__name__,
                                 'd_name': dec.__name__})
        return _decorator
    return _decorator_checker 
開發者ID:openstack,項目名稱:zun,代碼行數:21,代碼來源:utils.py

示例8: get_argCount

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargspec [as 別名]
def get_argCount(func) -> int:
    """獲取函數對象的參數個數

    def sum(a,b):
        return(a+b)
    print(sum.__code__.co_argcount) # 2

    #輸出的函數參數個數
    print(sum.__code__.co_varnames) # ('a', 'b')
    #這裏會輸出函數用到的所有變量名,不隻是參數名

    print(sum.__defaults__) # None
    # 返回參數的初始值

    import inspect
    inspect.getargspec(sum) #ArgSpec(args=['a', 'b'], varargs=None, keywords=None, defaults=None)

    :param func: 函數對象
    :return: 函數對象的參數個數
    """
    return func.__code__.co_argcount 
開發者ID:jtyoui,項目名稱:Jtyoui,代碼行數:23,代碼來源:methods.py

示例9: _get_check_functions

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargspec [as 別名]
def _get_check_functions(name=None, request=None):
    checks = _get_registered_health_checks()
    if not checks or (name and name not in checks):
        raise StopIteration()

    checks = _filter_checks_on_permission(request, checks)
    if not checks or (name and name not in checks):
        raise PermissionDenied()

    for service, func_string in checks.items():
        if name and name != service:
            continue

        if callable(func_string):
            check_func = func_string
        elif func_string.startswith(('https://', 'http://')):
            check_func = _http_healthcheck_func(func_string)
        else:
            check_func = import_string(func_string)

        spec = inspect.getargspec(check_func)
        if spec.args == ['request']:
            check_func = functools.partial(check_func, request)

        yield service, check_func 
開發者ID:mvantellingen,項目名稱:django-healthchecks,代碼行數:27,代碼來源:checker.py

示例10: version_kwargs

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargspec [as 別名]
def version_kwargs(d):
    """ Fix API calls for kwargs dict ``d`` that should have key ``estimator``
    """
    argspec = inspect.getargspec(CCDCesque.__init__)
    if 'estimator' in argspec.args:
        # Spec updated to estimator={object': ..., 'fit': {}}
        idx = [i for i, arg in enumerate(argspec.args)
               if arg == 'estimator'][0] - 1
        if isinstance(argspec.defaults[idx], dict):
            return d
        else:
            d['estimator'] = {'object': d['estimator'], 'fit': {}}
    elif 'lm' in argspec.args:
        new_key, old_key = 'lm', 'estimator'
        d[new_key] = d.pop(old_key)
        return d
    else:
        raise KeyError('Neither "lm" nor "estimator" are keys in '
                       'CCDCesque.__init__') 
開發者ID:ceholden,項目名稱:yatsm,代碼行數:21,代碼來源:ccdc.py

示例11: assert_docstring_includes_param_metadata

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargspec [as 別名]
def assert_docstring_includes_param_metadata(thing, path):
    if inspect.isclass(thing):
        return

    docstring = inspect.getdoc(thing)
    if not docstring:
        return

    for arg_name in inspect.getargspec(thing).args:
        if arg_name in ("self", "cls"):
            continue

        if ":param %s:" % arg_name not in docstring:
            raise AssertionError(
                "Missing :param: for arg %s of %s" % (arg_name, path)
            )
        if ":type %s:" % arg_name not in docstring:
            raise AssertionError(
                "Missing :type: for arg %s of %s" % (arg_name, path)
            ) 
開發者ID:wglass,項目名稱:collectd-haproxy,代碼行數:22,代碼來源:test_docstrings.py

示例12: filter_chain

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargspec [as 別名]
def filter_chain(filters, token, func, *args, **kwargs):
    if token == -1:
        return func()
    else:
        def _inner_method():
            fm = filters[token]
            fargs = getargspec(fm)[0]
            if len(fargs) == 1:
                # Only self arg
                result = func()
                if result is None:
                    return fm()
                else:
                    raise IncorrectPluginArg(u'Plugin filter method need a arg to receive parent method result.')
            else:
                return fm(func if fargs[1] == '__' else func(), *args, **kwargs)
        return filter_chain(filters, token - 1, _inner_method, *args, **kwargs) 
開發者ID:stormsha,項目名稱:StormOnline,代碼行數:19,代碼來源:base.py

示例13: _check_signature

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargspec [as 別名]
def _check_signature(self, fn, fn_description, *args, **kwargs):
        exception_msg = None

        if IS_PYTHON2:
            try:
                callable_ = fn if hasattr(fn, '__name__') else fn.__call__
                inspect.getcallargs(callable_, self, *args, **kwargs)
            except TypeError as exc:
                spec = inspect.getargspec(callable_)
                fn_params = list(spec.args)
                exception_msg = str(exc)
        else:
            signature = inspect.signature(fn)
            try:
                signature.bind(self, *args, **kwargs)
            except TypeError as exc:
                fn_params = list(signature.parameters)
                exception_msg = str(exc)

        if exception_msg:
            passed_params = [self] + list(args) + list(kwargs)
            raise ValueError("Error adding {} '{}': "
                             "takes parameters {} but will be called with {} "
                             "({})".format(
                                 fn, fn_description, fn_params, passed_params, exception_msg)) 
開發者ID:hrhodin,項目名稱:UnsupervisedGeometryAwareRepresentationLearning,代碼行數:27,代碼來源:engine.py

示例14: ModuleHasValidMainFunction

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargspec [as 別名]
def ModuleHasValidMainFunction(module):
  """Determines if a module has a main function that takes no arguments.

  This includes functions that have arguments with defaults that are all
  assigned, thus requiring no additional arguments in order to be called.

  Args:
    module: A types.ModuleType instance.

  Returns:
    True if the module has a valid, reusable main function; False otherwise.
  """
  if hasattr(module, 'main') and type(module.main) is types.FunctionType:
    arg_names, var_args, var_kwargs, default_values = inspect.getargspec(
        module.main)
    if len(arg_names) == 0:
      return True
    if default_values is not None and len(arg_names) == len(default_values):
      return True
  return False 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:22,代碼來源:dev_appserver.py

示例15: _each_subclass_instantiated_with_mock_args

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getargspec [as 別名]
def _each_subclass_instantiated_with_mock_args(self):
        """
        This returns an instantiated copy of each subclass of
        UpdatingMetadataWrapperBase, passing a MagicMock for each argument on
        initialization. This lets us test properties that should hold for all
        subclasses.

        I don't like having tests depend on this weird metaprogramming, but I'd
        rather have this, which generates tests for any future subclasses, than
        miss tests for them.
        """
        for klaus in UpdatingMetadataWrapperBase.__subclasses__():
            # get length of argument list for class init
            init_arg_len = len(inspect.getargspec(klaus.__init__)[0])
            # args list is one shorter -- argspec includes self
            init_args = [MagicMock() for _ in range(init_arg_len - 1)]
            yield klaus(*init_args) 
開發者ID:apache,項目名稱:cassandra-dtest,代碼行數:19,代碼來源:metadata_wrapper_test.py


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