本文整理汇总了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)
示例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))
示例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.
示例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
示例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)
示例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)
示例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))
示例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)
示例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