本文整理汇总了Python中inspect.getmro方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.getmro方法的具体用法?Python inspect.getmro怎么用?Python inspect.getmro使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类inspect
的用法示例。
在下文中一共展示了inspect.getmro方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_docstring_fields
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmro [as 别名]
def _get_docstring_fields(self):
"""
Collect custom serializer fields described in serializer docstring
:rtype: OrderedDict
"""
if not inspect.isclass(self.serializer):
self.serializer = self.serializer.__class__
parser = YAMLDocstringParser()
for cls in inspect.getmro(self.serializer):
parser.update(inspect.getdoc(cls))
doc_fields = parser.schema.get('fields', OrderedDict())
return doc_fields
示例2: trace_toolchain
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmro [as 别名]
def trace_toolchain(toolchain):
"""
Trace the versions of the involved packages for the provided
toolchain instance.
"""
pkgs = []
for cls in getmro(type(toolchain)):
if not issubclass(cls, Toolchain):
continue
dist = _cls_lookup_dist(cls)
value = {
'project_name': dist.project_name,
'version': dist.version,
} if dist else {}
key = '%s:%s' % (cls.__module__, cls.__name__)
pkgs.append({key: value})
return pkgs
示例3: is_power_of_two
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmro [as 别名]
def is_power_of_two(value):
"""Returns True if the given value is a positive power of two, False
otherwise."""
while value > 0:
if value == 1:
return True
elif (value & 1) == 1:
return False
value >>= 1
return False
#def inheritdocstring(cls):
# for base in inspect.getmro(cls):
# if base.__doc__ is not None:
# cls.__doc__ = base.__doc__
# break
# return cls
示例4: _get_def_class
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmro [as 别名]
def _get_def_class(self, class_obj, member_name):
"""
Return the class object in MRO order that defines a member.
class_obj: Class object that exposes (but not necessarily defines) the
member. I.e. starting point of the search.
member_name: Name of the member (method or attribute).
Returns:
Class object that defines the member.
"""
member_obj = getattr(class_obj, member_name)
for def_class_obj in inspect.getmro(class_obj):
if member_name in def_class_obj.__dict__:
if def_class_obj.__name__ in self._excluded_classes:
return class_obj # Fall back to input class
return def_class_obj
self._logger.warning(
"%s: Definition class not found for member %s.%s, "
"defaulting to class %s",
self._log_prefix, class_obj.__name__, member_name,
class_obj.__name__)
return class_obj # Input class is better than nothing
示例5: call_internal
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmro [as 别名]
def call_internal(self, func_modifier, args, kw):
""" Common utility class for calling an overloaded method,
either bound on a class or not. func_modifier is a lambda
function which is used to "bind" bound methods to the correct
instance
"""
argtype = type(args[0])
class Old:
pass
if argtype is types.InstanceType: # old-style class
argtype = args[0].__class__
hier = list(inspect.getmro(argtype)) # class hierarchy
hier.reverse() # order w/ superclass first
hier = [ t for t in hier if t in self.registry ]
if len(hier) == 0:
raise TypeError("Function %s has no compatible overloads registered for argument type %s" %
(self.func_name, argtype))
result = None
for t in hier:
if not self.allow_cascade[t] and t != hier[-1]:
continue # don't "cascade" down from superclass on this method
result = func_modifier(self.registry[t])(*args, **kw)
return result
示例6: __init_with_kwargs__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmro [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)
示例7: collect
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmro [as 别名]
def collect(self):
if not getattr(self.obj, "__test__", True):
return []
# NB. we avoid random getattrs and peek in the __dict__ instead
# (XXX originally introduced from a PyPy need, still true?)
dicts = [getattr(self.obj, "__dict__", {})]
for basecls in inspect.getmro(self.obj.__class__):
dicts.append(basecls.__dict__)
seen = {}
values = []
for dic in dicts:
for name, obj in list(dic.items()):
if name in seen:
continue
seen[name] = True
res = self._makeitem(name, obj)
if res is None:
continue
if not isinstance(res, list):
res = [res]
values.extend(res)
values.sort(key=lambda item: item.reportinfo()[:2])
return values
示例8: get_unpatched_class
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmro [as 别名]
def get_unpatched_class(cls):
"""Protect against re-patching the distutils if reloaded
Also ensures that no other distutils extension monkeypatched the distutils
first.
"""
external_bases = (
cls
for cls in inspect.getmro(cls)
if not cls.__module__.startswith('setuptools')
)
base = next(external_bases)
if not base.__module__.startswith('distutils'):
msg = "distutils has already been patched by %r" % cls
raise AssertionError(msg)
return base
示例9: register_api_methods_and_graph_fns
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmro [as 别名]
def register_api_methods_and_graph_fns(self):
"""
Detects all methods of the Component that should be registered as API-methods for
this Component and complements `self.api_methods` and `self.api_method_inputs`.
Goes by the @api decorator before each API-method or graph_fn that should be
auto-thin-wrapped by an API-method.
"""
# Goes through the class hierarchy of `self` and tries to lookup all registered functions
# (by name) that should be turned into API-methods.
class_hierarchy = inspect.getmro(type(self))
for class_ in class_hierarchy[:-2]: # skip last two as its `Specifiable` and `object`
api_method_recs = component_api_registry.get(class_.__name__)
if api_method_recs is not None:
for api_method_rec in api_method_recs:
if api_method_rec.name not in self.api_methods:
define_api_method(self, api_method_rec)
graph_fn_recs = component_graph_fn_registry.get(class_.__name__)
if graph_fn_recs is not None:
for graph_fn_rec in graph_fn_recs:
if graph_fn_rec.name not in self.graph_fns:
define_graph_fn(self, graph_fn_rec)
示例10: __get_visit_method
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmro [as 别名]
def __get_visit_method(self, type_):
"""
Returns a visit method for the given type_, or None if none could be
found.
"""
# Try all the type names in the target's MRO
for base in inspect.getmro(type_):
visit_name = "visit_{}".format(base.__name__)
# If we found a matching visit_TYPE method, return it
if hasattr(self, visit_name):
visit_method = getattr(self, visit_name)
return visit_method
# Not found => return None
return None
示例11: __init__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmro [as 别名]
def __init__(self, obj, members=None, exclude=None, exclude_inherited=False, lock=None):
super(ExposedObject, self).__init__()
self._object = obj
self._function_map = {}
self._lock = lock
self._add_function(':api', self.get_api)
exposed_members = members if members else self._public_members()
exclude = list(exclude or [])
if exclude_inherited:
for base in inspect.getmro(type(obj))[1:]:
exclude += dir(base)
for method in exposed_members:
if method not in exclude:
self._add_member_wrappers(method)
示例12: find_subtype
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmro [as 别名]
def find_subtype(component: Type[T]) -> Union[Type[T], None]:
def mro_distance(subtype: Type[T]) -> int:
mro = inspect.getmro(subtype)
return mro.index(component)
subtypes = [c for c in Context.current_context()
if issubclass(c, component)]
distances = [mro_distance(subtype) for subtype in subtypes]
counter = Counter(distances)
if any(count > 1 for count in counter.values()):
ambiguous = [str(subtype) for subtype in subtypes
if counter[mro_distance(subtype)] > 1]
message = ('Attempt to inject type {} with '
'equally specific provided subtypes: {}')
message = message.format(
str(component),
', '.join(ambiguous)
)
raise AmbiguousDependencies(message)
if not subtypes:
return None
return max(subtypes, key=mro_distance)
示例13: params
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmro [as 别名]
def params(cls):
params = list()
for name, value in inspect.getmembers(cls):
if not isinstance(value, Param):
continue
params.append((name, value))
keys = dict()
orders = dict()
for base in inspect.getmro(cls):
for name, value in inspect.getmembers(base):
if not isinstance(value, Param):
continue
bites = list(name.split("_"))
keys[name] = list()
for i in range(len(bites)):
key = tuple(bites[:i + 1])
keys[name].append(key)
orders[key] = min(orders.get(key, value.order), value.order)
return sorted(params, key=lambda x: tuple(map(orders.get, keys[x[0]])))
示例14: removeMethod
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmro [as 别名]
def removeMethod(self, klass, methodName):
"""
Remove 'methodName' from 'klass'.
If 'klass' does not have a method named 'methodName', then
'removeMethod' succeeds silently.
If 'klass' does have a method named 'methodName', then it is removed
using delattr. Also, methods of the same name are removed from all
base classes of 'klass', thus removing the method entirely.
@param klass: The class to remove the method from.
@param methodName: The name of the method to remove.
"""
method = getattr(klass, methodName, None)
if method is None:
return
for base in getmro(klass):
try:
delattr(base, methodName)
except (AttributeError, TypeError):
break
else:
self.addCleanup(setattr, base, methodName, method)
示例15: _aybabtu
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmro [as 别名]
def _aybabtu(c):
"""
Get all of the parent classes of C{c}, not including C{c} itself, which are
strict subclasses of L{Versioned}.
@param c: a class
@returns: list of classes
"""
# begin with two classes that should *not* be included in the
# final result
l = [c, Versioned]
for b in inspect.getmro(c):
if b not in l and issubclass(b, Versioned):
l.append(b)
# return all except the unwanted classes
return l[2:]