本文整理汇总了Python中inspect.isroutine方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.isroutine方法的具体用法?Python inspect.isroutine怎么用?Python inspect.isroutine使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类inspect
的用法示例。
在下文中一共展示了inspect.isroutine方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isroutine [as 别名]
def __init__(self, function, args=(), kwargs={}):
"""Constructor.
:param function: Python method to run.
:type function: routine
:param args: Argument list to run the method with.
:type args: tuple
:param kwargs: Keyword arguments to run the method with.
:type kwargs: dict
"""
assert isroutine(function), "Python callable expected"
assert isinstance(args, tuple)
assert isinstance(kwargs, dict)
super(Job, self).__init__(function.__name__)
self.function = function
self.args = args
self.kwargs = kwargs
示例2: document
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isroutine [as 别名]
def document(self, object, name=None, *args):
"""Generate documentation for an object."""
args = (object, name) + args
# 'try' clause is to attempt to handle the possibility that inspect
# identifies something in a way that pydoc itself has issues handling;
# think 'super' and how it is a descriptor (which raises the exception
# by lacking a __name__ attribute) and an instance.
if inspect.isgetsetdescriptor(object): return self.docdata(*args)
if inspect.ismemberdescriptor(object): return self.docdata(*args)
try:
if inspect.ismodule(object): return self.docmodule(*args)
if inspect.isclass(object): return self.docclass(*args)
if inspect.isroutine(object): return self.docroutine(*args)
except AttributeError:
pass
if isinstance(object, property): return self.docproperty(*args)
return self.docother(*args)
示例3: render_doc
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isroutine [as 别名]
def render_doc(thing, title='Python Library Documentation: %s', forceload=0,
renderer=None):
"""Render text documentation, given an object or a path to an object."""
if renderer is None:
renderer = text
object, name = resolve(thing, forceload)
desc = describe(object)
module = inspect.getmodule(object)
if name and '.' in name:
desc += ' in ' + name[:name.rfind('.')]
elif module and module is not object:
desc += ' in module ' + module.__name__
if not (inspect.ismodule(object) or
inspect.isclass(object) or
inspect.isroutine(object) or
inspect.isgetsetdescriptor(object) or
inspect.ismemberdescriptor(object) or
isinstance(object, property)):
# If the passed object is a piece of data or an instance,
# document its available methods instead of its value.
object = type(object)
desc += ' object'
return title % desc + '\n\n' + renderer.document(object, name)
示例4: get_client_method_names
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isroutine [as 别名]
def get_client_method_names() -> List[str]:
"""Extracts method names from LookerClient to test for bad responses"""
client_members: List[Tuple[str, Callable]] = inspect.getmembers(
LookerClient, predicate=inspect.isroutine
)
client_methods: List[str] = [
member[0] for member in client_members if not member[0].startswith("__")
]
for skip_method in (
"authenticate",
"cancel_query_task",
"request",
"get",
"post",
"put",
"patch",
"delete",
):
client_methods.remove(skip_method)
return client_methods
示例5: parse_hookimpl_opts
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isroutine [as 别名]
def parse_hookimpl_opts(self, plugin, name):
method = getattr(plugin, name)
if not inspect.isroutine(method):
return
try:
res = getattr(method, self.project_name + "_impl", None)
except Exception:
res = {}
if res is not None and not isinstance(res, dict):
# false positive
res = None
# TODO: remove when we drop implprefix in 1.0
elif res is None and self._implprefix and name.startswith(self._implprefix):
_warn_for_function(
DeprecationWarning(
"The `implprefix` system is deprecated please decorate "
"this function using an instance of HookimplMarker."
),
method,
)
res = {}
return res
示例6: render_doc
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isroutine [as 别名]
def render_doc(thing, title='Python Library Documentation: %s', forceload=0):
"""Render text documentation, given an object or a path to an object."""
object, name = resolve(thing, forceload)
desc = describe(object)
module = inspect.getmodule(object)
if name and '.' in name:
desc += ' in ' + name[:name.rfind('.')]
elif module and module is not object:
desc += ' in module ' + module.__name__
if type(object) is _OLD_INSTANCE_TYPE:
# If the passed object is an instance of an old-style class,
# document its available methods instead of its value.
object = object.__class__
elif not (inspect.ismodule(object) or
inspect.isclass(object) or
inspect.isroutine(object) or
inspect.isgetsetdescriptor(object) or
inspect.ismemberdescriptor(object) or
isinstance(object, property)):
# If the passed object is a piece of data or an instance,
# document its available methods instead of its value.
object = type(object)
desc += ' object'
return title % desc + '\n\n' + text.document(object, name)
示例7: _mod_info
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isroutine [as 别名]
def _mod_info(modname, toskip=[], onlylocals=True):
"""
Determines if a module is a module or a package and whether or not
it has classes or functions.
"""
hascls = hasfunc = False
for localnm, fqnm, obj in zip(*find_mod_objs(modname, onlylocals=onlylocals)):
if localnm not in toskip:
hascls = hascls or inspect.isclass(obj)
hasfunc = hasfunc or inspect.isroutine(obj)
if hascls and hasfunc:
break
# find_mod_objs has already imported modname
# TODO: There is probably a cleaner way to do this, though this is pretty
# reliable for all Python versions for most cases that we care about.
pkg = sys.modules[modname]
ispkg = (hasattr(pkg, '__file__') and isinstance(pkg.__file__, str) and
os.path.split(pkg.__file__)[1].startswith('__init__.py'))
return ispkg, hascls, hasfunc
示例8: get_attributes
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isroutine [as 别名]
def get_attributes(self):
attributes = inspect.getmembers(self, lambda a: not (inspect.isroutine(a)))
# store only not the default attribute __xx__
attribute_tuple_list = [a for a in attributes if not (a[0].startswith('__') and a[0].endswith('__'))]
attribute_dict = {}
for tup in attribute_tuple_list:
key = tup[0]
value = tup[1]
if key == 'loss':
value = str(value)
# convert numpy value to float
if type(value) == np.float64:
value = float(value)
attribute_dict[key] = value
return attribute_dict
示例9: denormalize
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isroutine [as 别名]
def denormalize(self):
"""
Create new config object that inherits all explicit attributes from
its parents as well.
"""
new_options = {}
for key in self._options:
value = getattr(self, key)
if inspect.isclass(value) or inspect.isroutine(value):
# Skipping non-serializable classes and routines.
logger.TESTPLAN_LOGGER.debug(
"Skip denormalizing option: %s", key
)
continue
try:
new_options[copy.deepcopy(key)] = copy.deepcopy(value)
except Exception as exc:
logger.TESTPLAN_LOGGER.warning(
"Failed to denormalize option: {} - {}".format(key, exc)
)
new = self.__class__(**new_options)
return new
示例10: failover_all_class_methods
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isroutine [as 别名]
def failover_all_class_methods(decorator):
"""
This decorator function wraps an entire class to decorate each member method, incl. inherited.
Adapted from https://stackoverflow.com/a/6307868
"""
# Convenience function to ensure `decorate` gets wrapper function attributes: name, docs, etc.
@functools.wraps(decorator)
def decorate(cls):
all_methods = inspect.getmembers(cls, inspect.isbuiltin) \
+ inspect.getmembers(cls, inspect.ismethod) \
+ inspect.getmembers(cls, inspect.isroutine)
for name, method in all_methods:
if not name.startswith('_'):
# It's safer to exclude all protected/private method from decoration
setattr(cls, name, decorator(method))
return cls
return decorate
示例11: _get_handlers
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isroutine [as 别名]
def _get_handlers(self, args, kwargs):
'''Implement handler matching on arguments for set_handlers and
remove_handlers.
'''
for object in args:
if inspect.isroutine(object):
# Single magically named function
name = object.__name__
if name not in self.event_types:
raise EventException('Unknown event "%s"' % name)
yield name, object
else:
# Single instance with magically named methods
for name in dir(object):
if name in self.event_types:
yield name, getattr(object, name)
for name, handler in kwargs.items():
# Function for handling given event (no magic)
if name not in self.event_types:
raise EventException('Unknown event "%s"' % name)
yield name, handler
示例12: isdata
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isroutine [as 别名]
def isdata(object):
"""Check if an object is of a type that probably means it's data."""
return not (inspect.ismodule(object) or inspect.isclass(object) or
inspect.isroutine(object) or inspect.isframe(object) or
inspect.istraceback(object) or inspect.iscode(object))
示例13: parse_hookimpl_opts
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isroutine [as 别名]
def parse_hookimpl_opts(self, plugin, name):
# pytest hooks are always prefixed with pytest_
# so we avoid accessing possibly non-readable attributes
# (see issue #1073)
if not name.startswith("pytest_"):
return
# ignore names which can not be hooks
if name == "pytest_plugins":
return
method = getattr(plugin, name)
opts = super().parse_hookimpl_opts(plugin, name)
# consider only actual functions for hooks (#3775)
if not inspect.isroutine(method):
return
# collect unmarked hooks as long as they have the `pytest_' prefix
if opts is None and name.startswith("pytest_"):
opts = {}
if opts is not None:
# TODO: DeprecationWarning, people should use hookimpl
# https://github.com/pytest-dev/pytest/issues/4562
known_marks = {m.name for m in getattr(method, "pytestmark", [])}
for name in ("tryfirst", "trylast", "optionalhook", "hookwrapper"):
opts.setdefault(name, hasattr(method, name) or name in known_marks)
return opts
示例14: isroutine
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isroutine [as 别名]
def isroutine(object): # pylint: disable=redefined-builtin
"""TFDecorator-aware replacement for inspect.isroutine."""
return _inspect.isroutine(tf_decorator.unwrap(object)[1])
示例15: collect_class_methods
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isroutine [as 别名]
def collect_class_methods(cls, methods):
if isinstance(methods, (list, tuple)):
return [getattr(cls, m) if isinstance(m, str) else m for m in methods]
methods = []
for _, method in inspect.getmembers(cls, predicate=inspect.isroutine):
if method.__name__[0] == '_' or method.__name__ in EXCLUDE:
continue
methods.append(method)
return methods