本文整理匯總了Python中inspect.getfullargspec方法的典型用法代碼示例。如果您正苦於以下問題:Python inspect.getfullargspec方法的具體用法?Python inspect.getfullargspec怎麽用?Python inspect.getfullargspec使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類inspect
的用法示例。
在下文中一共展示了inspect.getfullargspec方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: store_args
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfullargspec [as 別名]
def store_args(method):
"""Stores provided method args as instance attributes.
"""
argspec = inspect.getfullargspec(method)
defaults = {}
if argspec.defaults is not None:
defaults = dict(
zip(argspec.args[-len(argspec.defaults):], argspec.defaults))
if argspec.kwonlydefaults is not None:
defaults.update(argspec.kwonlydefaults)
arg_names = argspec.args[1:]
@functools.wraps(method)
def wrapper(*positional_args, **keyword_args):
self = positional_args[0]
# Get default arg values
args = defaults.copy()
# Add provided arg values
for name, value in zip(arg_names, positional_args[1:]):
args[name] = value
args.update(keyword_args)
self.__dict__.update(args)
return method(*positional_args, **keyword_args)
return wrapper
示例2: get_config_file
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfullargspec [as 別名]
def get_config_file(self):
config = {
"input_interfaces": [
(iface.__class__.__name__.lower(), iface.get_template_context())
for iface in self.input_interfaces],
"output_interfaces": [
(iface.__class__.__name__.lower(), iface.get_template_context())
for iface in self.output_interfaces],
"function_count": len(self.predict),
"live": self.live,
"show_input": self.show_input,
"show_output": self.show_output,
"title": self.title,
"description": self.description,
"thumbnail": self.thumbnail
}
try:
param_names = inspect.getfullargspec(self.predict[0])[0]
for iface, param in zip(config["input_interfaces"], param_names):
if not iface[1]["label"]:
iface[1]["label"] = param.replace("_", " ")
except ValueError:
pass
return config
示例3: schedule_handler
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfullargspec [as 別名]
def schedule_handler(cls: Any, obj: Any, context: Dict, func: Any, interval: Optional[Union[str, int]] = None, timestamp: Optional[str] = None, timezone: Optional[str] = None, immediately: Optional[bool] = False) -> Any:
async def handler() -> None:
values = inspect.getfullargspec(func)
kwargs = {k: values.defaults[i] for i, k in enumerate(values.args[len(values.args) - len(values.defaults):])} if values.defaults else {}
try:
routine = func(*(obj,), **kwargs)
if isinstance(routine, Awaitable):
await routine
except Exception as e:
logging.getLogger('exception').exception('Uncaught exception: {}'.format(str(e)))
context['_schedule_scheduled_functions'] = context.get('_schedule_scheduled_functions', [])
context['_schedule_scheduled_functions'].append((interval, timestamp, timezone, immediately, func, handler))
start_func = cls.start_scheduler(cls, obj, context)
return (await start_func) if start_func else None
示例4: make_step_from_method
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfullargspec [as 別名]
def make_step_from_method(func: Callable[[], bool], name: str = "") -> HammerToolStep:
"""
Create a HammerToolStep from a method.
:param func: Method for the given substep (e.g. self.elaborate)
:param name: Name of the hook. If unspecified, defaults to func.__name__.
:return: A HammerToolStep defining this step.
"""
if not callable(func):
raise TypeError("func is not callable")
if not hasattr(func, "__self__"):
raise ValueError("This function does not take unbound functions")
annotations = inspect.getfullargspec(func).annotations
if annotations != {'return': bool}:
raise TypeError("Function {func} does not meet the required signature".format(func=str(func)))
# Wrapper to make __func__ take a proper type annotation for "self"
def wrapper(x: HammerTool) -> bool:
return func.__func__(x) # type: ignore # no type stub for builtin __func__
if name == "":
name = func.__name__
return make_raw_hammer_tool_step(func=wrapper, name=name)
示例5: validate_url
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfullargspec [as 別名]
def validate_url(wrapped, instance, args, kwargs):
"""Enforces argument named "url" to be relative path.
Check that it is instance of str or os.PathLike and that it represents
relative path.
"""
try:
# Use -1 since self is not included in the args.
url = args[getfullargspec(wrapped).args.index("url") - 1]
except IndexError:
url = kwargs.get("url")
if not isinstance(url, (str, PathLike)):
raise TypeError("Argument 'url' must be a string or path-like object")
if PurePath(url).is_absolute():
raise ValueError("Argument 'url' must be a relative path")
return wrapped(*args, **kwargs)
示例6: validate_urls
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfullargspec [as 別名]
def validate_urls(wrapped, instance, args, kwargs):
"""Enforces argument named "urls" to be a list of relative paths."""
try:
# Use -1 since self is not included in the args.
urls = args[getfullargspec(wrapped).args.index("urls") - 1]
except IndexError:
urls = kwargs.get("urls")
# Check that URLS is really a list of strings.
if not isinstance(urls, list):
raise TypeError("Argument urls must be a list of strings or path-like objects")
if not all(isinstance(url, (str, PathLike)) for url in urls):
raise TypeError("Argument urls must be a list of strings or path-like objects")
# Check that all URLS are relative.
if any(PurePath(url).is_absolute() for url in urls):
raise ValueError("Paths must be relative.")
return wrapped(*args, *kwargs)
示例7: _getArgSpec
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfullargspec [as 別名]
def _getArgSpec(func):
"""
Normalize inspect.ArgSpec across python versions
and convert mutable attributes to immutable types.
:param Callable func: A function.
:return: The function's ArgSpec.
:rtype: ArgSpec
"""
spec = getArgsSpec(func)
return ArgSpec(
args=tuple(spec.args),
varargs=spec.varargs,
varkw=spec.varkw if six.PY3 else spec.keywords,
defaults=spec.defaults if spec.defaults else (),
kwonlyargs=tuple(spec.kwonlyargs) if six.PY3 else (),
kwonlydefaults=(
tuple(spec.kwonlydefaults.items())
if spec.kwonlydefaults else ()
) if six.PY3 else (),
annotations=tuple(spec.annotations.items()) if six.PY3 else (),
)
示例8: __init_with_kwargs__
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfullargspec [as 別名]
def __init_with_kwargs__(cls, self, kwargs, **fallbacks):
if not hasattr(self, '_Duct__inited_using_kwargs'):
self._Duct__inited_using_kwargs = {}
for cls_parent in reversed([
parent for parent in inspect.getmro(cls)
if issubclass(parent, Duct)
and parent not in self._Duct__inited_using_kwargs
and '__init__' in parent.__dict__
]):
self._Duct__inited_using_kwargs[cls_parent] = True
if six.PY3:
argspec = inspect.getfullargspec(cls_parent.__init__)
keys = argspec.args[1:] + argspec.kwonlyargs
else:
keys = inspect.getargspec(cls_parent.__init__).args[1:]
params = {}
for key in keys:
if key in kwargs:
params[key] = kwargs.pop(key)
elif key in fallbacks:
params[key] = fallbacks[key]
cls_parent.__init__(self, **params)
示例9: df_apply
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfullargspec [as 別名]
def df_apply(df, func, axis=0, raw=False, result_type=None, args=(), dtypes=None,
output_type=None, index=None, elementwise=None, **kwds):
if isinstance(func, (list, dict)):
return df.aggregate(func)
if isinstance(output_type, str):
output_type = getattr(OutputType, output_type.lower())
# calling member function
if isinstance(func, str):
func = getattr(df, func)
sig = inspect.getfullargspec(func)
if "axis" in sig.args:
kwds["axis"] = axis
return func(*args, **kwds)
op = ApplyOperand(func=func, axis=axis, raw=raw, result_type=result_type, args=args, kwds=kwds,
output_type=output_type, elementwise=elementwise)
return op(df, dtypes=dtypes, index=index)
示例10: execute_agg
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfullargspec [as 別名]
def execute_agg(cls, ctx, op):
(input_chunk,), device_id, xp = as_same_device(
[ctx[c.key] for c in op.inputs], device=op.device, ret_extra=True)
axis = cls.get_axis(op.axis)
func_name = getattr(cls, '_func_name', None)
reduce_func = getattr(xp, func_name)
out = op.outputs[0]
with device(device_id):
if "dtype" in inspect.getfullargspec(reduce_func).args:
ret = reduce_func(input_chunk, axis=axis,
dtype=op.dtype,
keepdims=bool(op.keepdims))
else:
ret = reduce_func(input_chunk, axis=axis,
keepdims=bool(op.keepdims))
ctx[out.key] = ret.astype(op.dtype, order=out.order.value, copy=False)
示例11: safe_kwargs
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfullargspec [as 別名]
def safe_kwargs(func_or_class):
from ..types.base import AliceObject
spec = getfullargspec(func_or_class)
all_args = spec.args
save_raw_kwargs = isclass(func_or_class) and issubclass(func_or_class, AliceObject)
@functools.wraps(func_or_class)
def wrap(*args, **kwargs):
accepted_kwargs = {k: v for k, v in kwargs.items() if k in all_args}
res = func_or_class(*args, **accepted_kwargs)
if save_raw_kwargs:
# saving all kwargs for access to unexpected attrs
res._raw_kwargs.update(kwargs)
return res
return wrap
示例12: test_customcatpcha_params
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfullargspec [as 別名]
def test_customcatpcha_params(self):
default_init_params = [
"self",
"anticaptcha_key",
"sleep_time",
"save_format",
"language",
"callbackUrl",
]
default_handler_params = ["self", "captcha_link", "captcha_file", "captcha_base64"]
# get customcaptcha init and captcha_handler params
aioinit_params = inspect.getfullargspec(ImageToTextTask.aioImageToTextTask.__init__)
aiohandler_params = inspect.getfullargspec(
ImageToTextTask.aioImageToTextTask.captcha_handler
)
# get customcaptcha init and captcha_handler params
init_params = inspect.getfullargspec(ImageToTextTask.ImageToTextTask.__init__)
handler_params = inspect.getfullargspec(ImageToTextTask.ImageToTextTask.captcha_handler)
# check aio module params
assert default_init_params == aioinit_params[0]
assert default_handler_params == aiohandler_params[0]
# check sync module params
assert default_init_params == init_params[0]
assert default_handler_params == handler_params[0]
示例13: test_nocaptcha_params
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfullargspec [as 別名]
def test_nocaptcha_params(self):
default_init_params = ["self", "anticaptcha_key", "sleep_time", "callbackUrl"]
default_handler_params = ["self", "websiteURL", "websiteKey", 'recaptchaDataSValue']
# get customcaptcha init and captcha_handler params
aioinit_params = inspect.getfullargspec(NoCaptchaTask.aioNoCaptchaTask.__init__)
aiohandler_params = inspect.getfullargspec(NoCaptchaTask.aioNoCaptchaTask.captcha_handler)
# get customcaptcha init and captcha_handler params
init_params = inspect.getfullargspec(NoCaptchaTask.NoCaptchaTask.__init__)
handler_params = inspect.getfullargspec(NoCaptchaTask.NoCaptchaTask.captcha_handler)
# check aio module params
assert default_init_params == aioinit_params[0]
assert default_handler_params == aiohandler_params[0]
# check sync module params
assert default_init_params == init_params[0]
assert default_handler_params == handler_params[0]
示例14: test_result_handler_params
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfullargspec [as 別名]
def test_result_handler_params(self):
default_init_params = ["self", "anticaptcha_key", "sleep_time"]
default_handler_params = ["self", "task_id"]
# get customcaptcha init and task_handler params
aioinit_params = inspect.getfullargspec(
CustomResultHandler.aioCustomResultHandler.__init__
)
aiohandler_params = inspect.getfullargspec(
CustomResultHandler.aioCustomResultHandler.task_handler
)
# get customcaptcha init and task_handler params
init_params = inspect.getfullargspec(CustomResultHandler.CustomResultHandler.__init__)
handler_params = inspect.getfullargspec(
CustomResultHandler.CustomResultHandler.task_handler
)
# check aio module params
assert default_init_params == aioinit_params[0]
assert default_handler_params == aiohandler_params[0]
# check sync module params
assert default_init_params == init_params[0]
assert default_handler_params == handler_params[0]
示例15: analyze_args
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getfullargspec [as 別名]
def analyze_args(self, func, module_function=False):
sig = inspect.signature(func)
argspec = inspect.getfullargspec(func)
parameter_count = 0
for k, v in sig.parameters.items():
# TODO improve it
if k == 'kwargs':
continue
parameter_count += 1
isSelfRemoved = not module_function and parameter_count != len(argspec.args) + len(argspec.kwonlyargs)
if isSelfRemoved:
self.add_arg(argspec.args[0], None)
for k, v in sig.parameters.items():
# TODO improve it
if k == 'kwargs':
continue
self.add_arg(v.name, values.parse_instance(None, v.name, v.default))