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


Python funcsigs.Signature方法代碼示例

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


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

示例1: create_signature

# 需要導入模塊: import funcsigs [as 別名]
# 或者: from funcsigs import Signature [as 別名]
def create_signature(args, optional_args):
    """ Dynamically create a signature for a function from strings.

    This function can be used to create a signature for a dynamically
    generated function without generating a string representation of
    the function code and making an explicit eval call.

    Parameters
    ----------
    args : list
        List of strings that name the required arguments of a function.
    optional_args : list
        List of strings that name the optional arguments of a function.

    Returns
    -------
    Signature(p) : inspect.Signature instance
        A Signature object that can be used to validate arguments in
        a dynamically created function.
    """
    p = [Parameter(x, Parameter.POSITIONAL_OR_KEYWORD) for x in args]
    p += [Parameter(x, Parameter.KEYWORD_ONLY, default='DEFAULT')
          for x in optional_args]
    return Signature(p) 
開發者ID:civisanalytics,項目名稱:civis-python,代碼行數:26,代碼來源:_resources.py

示例2: __call__

# 需要導入模塊: import funcsigs [as 別名]
# 或者: from funcsigs import Signature [as 別名]
def __call__(self, *args, **kwargs):
        """
        Evaluate the model for a certain value of the independent vars and parameters.
        Signature for this function contains independent vars and parameters, NOT dependent and sigma vars.

        Can be called with both ordered and named parameters. Order is independent vars first, then parameters.
        Alphabetical order within each group.

        :param args: Ordered arguments for the parameters and independent
          variables
        :param kwargs:  Keyword arguments for the parameters and independent
          variables
        :return: A namedtuple of all the dependent vars evaluated at the desired point. Will always return a tuple,
            even for scalar valued functions. This is done for consistency.
        """
        return ModelOutput(self.keys(), self.eval_components(*args, **kwargs)) 
開發者ID:tBuLi,項目名稱:symfit,代碼行數:18,代碼來源:models.py

示例3: _np_signature

# 需要導入模塊: import funcsigs [as 別名]
# 或者: from funcsigs import Signature [as 別名]
def _np_signature(f):
  """An enhanced funcsigs.signature that can handle numpy.ufunc."""
  if not isinstance(f, np.ufunc):
    return funcsigs.signature(f)
  def names_from_num(prefix, n):
    if n <= 0:
      return []
    elif n == 1:
      return [prefix]
    else:
      return [prefix + str(i + 1) for i in range(n)]
  input_names = names_from_num('x', f.nin)
  output_names = names_from_num('out', f.nout)
  keyword_only_params = [
      ('where', True),
      ('casting', 'same_kind'),
      ('order', 'K'),
      ('dtype', None),
      ('subok', True),
      ('signature', None),
      ('extobj', None)]
  params = []
  params += [funcsigs.Parameter(name, funcsigs.Parameter.POSITIONAL_ONLY)
             for name in input_names]
  if f.nout > 1:
    params += [funcsigs.Parameter(name, funcsigs.Parameter.POSITIONAL_ONLY,
                                  default=None)
               for name in output_names]
  params += [funcsigs.Parameter(
      'out', funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
      default=None if f.nout == 1 else (None,) * f.nout)]
  params += [funcsigs.Parameter(name, funcsigs.Parameter.KEYWORD_ONLY,
                                default=default)
             for name, default in keyword_only_params]
  return funcsigs.Signature(params)


# Python 2 doesn't allow keyword-only argument. Python prior to 3.8 doesn't
# allow positional-only argument. So we conflate positional-only, keyword-only
# and positional-or-keyword arguments here. 
開發者ID:google,項目名稱:trax,代碼行數:42,代碼來源:utils.py

示例4: __signature__

# 需要導入模塊: import funcsigs [as 別名]
# 或者: from funcsigs import Signature [as 別名]
def __signature__(self):
        if hasattr(self, '__customsig'):
            return self.__customsig

        kwargs = []
        for param in self.PARAMETERS:
            kwargs.append(funcsigs.Parameter(param.name,
                                             default=param.default,
                                             kind=funcsigs.Parameter.POSITIONAL_OR_KEYWORD))

        self.__customsig = funcsigs.Signature(kwargs, __validate_parameters__=True)
        return self.__customsig 
開發者ID:Autodesk,項目名稱:molecular-design-toolkit,代碼行數:14,代碼來源:method.py

示例5: _make_signature

# 需要導入模塊: import funcsigs [as 別名]
# 或者: from funcsigs import Signature [as 別名]
def _make_signature(self):
        # Handle args and kwargs according to the allowed names.
        parameters = [
            # Note that these are inspect_sig.Parameter's, not symfit parameters!
            inspect_sig.Parameter(arg.name,
                                  inspect_sig.Parameter.POSITIONAL_OR_KEYWORD)
            for arg in self.independent_vars + self.params
        ]
        return inspect_sig.Signature(parameters=parameters) 
開發者ID:tBuLi,項目名稱:symfit,代碼行數:11,代碼來源:models.py

示例6: _make_signature

# 需要導入模塊: import funcsigs [as 別名]
# 或者: from funcsigs import Signature [as 別名]
def _make_signature(self):
        """
        Make a :class:`inspect.Signature` object corresponding to
        ``self.model``.

        :return: :class:`inspect.Signature` object corresponding to
            ``self.model``.
        """
        parameters = self._make_parameters(self.model)
        parameters = sorted(parameters, key=lambda p: p.default is None)
        return inspect_sig.Signature(parameters=parameters) 
開發者ID:tBuLi,項目名稱:symfit,代碼行數:13,代碼來源:fit.py

示例7: _make_signature

# 需要導入模塊: import funcsigs [as 別名]
# 或者: from funcsigs import Signature [as 別名]
def _make_signature(self):
        """
        Create a signature for `execute` based on the minimizers this
        `ChainedMinimizer` was initiated with. For the format, see the docstring
        of :meth:`ChainedMinimizer.execute`.

        :return: :class:`inspect.Signature` instance.
        """
        # Create KEYWORD_ONLY arguments with the names of the minimizers.
        name = lambda x: x.__class__.__name__
        count = Counter(
            [name(minimizer) for minimizer in self.minimizers]
        ) # Count the number of each minimizer, they don't have to be unique

        # Note that these are inspect_sig.Parameter's, not symfit parameters!
        parameters = []
        for minimizer in reversed(self.minimizers):
            if count[name(minimizer)] == 1:
                # No ambiguity, so use the name directly.
                param_name = name(minimizer)
            else:
                # Ambiguity, so append the number of remaining minimizers
                param_name = '{}_{}'.format(name(minimizer), count[name(minimizer)])
            count[name(minimizer)] -= 1

            parameters.append(
                inspect_sig.Parameter(
                    param_name,
                    kind=inspect_sig.Parameter.KEYWORD_ONLY,
                    default={}
                )
            )
        return inspect_sig.Signature(parameters=reversed(parameters)) 
開發者ID:tBuLi,項目名稱:symfit,代碼行數:35,代碼來源:minimizers.py

示例8: test_vqe_run

# 需要導入模塊: import funcsigs [as 別名]
# 或者: from funcsigs import Signature [as 別名]
def test_vqe_run():
    """
    VQE initialized and then minimizer is called to return result.

    Checks correct sequence of execution.
    """
    def param_prog(alpha):
        return Program([H(0), RZ(alpha)(0)])

    hamiltonian = np.array([[1, 0], [0, -1]])
    initial_param = 0.0

    minimizer = MagicMock(spec=minimize, func_code=minimize.__code__)
    fake_result = Mock()
    fake_result.fun = 1.0
    fake_result.x = [0.0]
    fake_result.status = 0  # adding so we avoid writing to logger
    minimizer.return_value = fake_result

    # not actually called in VQE run since we are overriding minmizer to just
    # return a value. Still need this so I don't try to call the QVM server.
    fake_qvm = Mock(spec=['wavefunction'])

    with patch("funcsigs.signature") as patch_signature:
        func_sigs_fake = MagicMock(spec=funcsigs.Signature)
        func_sigs_fake.parameters.return_value = \
            OrderedDict({
                'fun': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'x0': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'args': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'method': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'jac': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'hess': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'hessp': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'bounds': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'constraints': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'tol': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'callback': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'options': funcsigs.Parameter.POSITIONAL_OR_KEYWORD
            })

        patch_signature.return_value = func_sigs_fake
        inst = VQE(minimizer)

        t_result = inst.vqe_run(param_prog, hamiltonian, initial_param, qc=fake_qvm)
        assert np.isclose(t_result.fun, 1.0) 
開發者ID:rigetti,項目名稱:grove,代碼行數:48,代碼來源:test_algorithms.py

示例9: call

# 需要導入模塊: import funcsigs [as 別名]
# 或者: from funcsigs import Signature [as 別名]
def call(self, *values, **named_values):
    """
    Call an expression to evaluate it at the given point.

    Future improvements: I would like if func and signature could be buffered after the
    first call so they don't have to be recalculated for every call. However, nothing
    can be stored on self as sympy uses __slots__ for efficiency. This means there is no
    instance dict to put stuff in! And I'm pretty sure it's ill advised to hack into the
    __slots__ of Expr.

    However, for the moment I don't really notice a performance penalty in running tests.

    p.s. In the current setup signature is not even needed since no introspection is possible
    on the Expr before calling it anyway, which makes calculating the signature absolutely useless.
    However, I hope that someday some monkey patching expert in shining armour comes by and finds
    a way to store it in __signature__ upon __init__ of any ``symfit`` expr such that calling
    inspect_sig.signature on a symbolic expression will tell you which arguments to provide.

    :param self: Any subclass of sympy.Expr
    :param values: Values for the Parameters and Variables of the Expr.
    :param named_values: Values for the vars and params by name. ``named_values`` is
        allowed to contain too many values, as this sometimes happens when using
        \*\*fit_result.params on a submodel. The irrelevant params are simply ignored.
    :return: The function evaluated at ``values``. The type depends entirely on the input.
        Typically an array or a float but nothing is enforced.
    """
    independent_vars, params = seperate_symbols(self)
    # Convert to a pythonic function
    func = sympy_to_py(self, independent_vars + params)

    # Handle args and kwargs according to the allowed names.
    parameters = [  # Note that these are inspect_sig.Parameter's, not symfit parameters!
        inspect_sig.Parameter(arg.name, inspect_sig.Parameter.POSITIONAL_OR_KEYWORD)
            for arg in independent_vars + params
    ]

    arg_names = [arg.name for arg in independent_vars + params]
    relevant_named_values = {
        name: value for name, value in named_values.items() if name in arg_names
    }

    signature = inspect_sig.Signature(parameters=parameters)
    bound_arguments = signature.bind(*values, **relevant_named_values)

    return func(**bound_arguments.arguments)


# # Expr.__eq__ = eq
# # Expr.__ne__ = ne 
開發者ID:tBuLi,項目名稱:symfit,代碼行數:51,代碼來源:operators.py


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