Python inspect.getmro() Examples
The following are 30
code examples of inspect.getmro().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
inspect
, or try the search function
.
Example #1
Source File: python.py From python-netsurv with MIT License | 6 votes |
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
Example #2
Source File: artifact.py From calmjs with GNU General Public License v2.0 | 6 votes |
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
Example #3
Source File: bot.py From abusehelper with MIT License | 6 votes |
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]])))
Example #4
Source File: Tools.py From joeecc with GNU General Public License v3.0 | 6 votes |
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
Example #5
Source File: monkey.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
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
Example #6
Source File: serializer.py From py2swagger with MIT License | 6 votes |
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
Example #7
Source File: test_reporter.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
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)
Example #8
Source File: _context.py From serum with MIT License | 6 votes |
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)
Example #9
Source File: conf.py From python-zhmcclient with Apache License 2.0 | 6 votes |
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
Example #10
Source File: duct.py From omniduct with MIT License | 6 votes |
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)
Example #11
Source File: styles.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
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:]
Example #12
Source File: control_server.py From lewis with GNU General Public License v3.0 | 6 votes |
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)
Example #13
Source File: monkey.py From python-netsurv with MIT License | 6 votes |
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
Example #14
Source File: python.py From python-netsurv with MIT License | 6 votes |
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
Example #15
Source File: patterns.py From MadMax with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #16
Source File: component.py From rlgraph with Apache License 2.0 | 6 votes |
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)
Example #17
Source File: visitor.py From yamdwe with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #18
Source File: monkey.py From ironpython2 with Apache License 2.0 | 5 votes |
def _get_mro(cls): """ Returns the bases classes for cls sorted by the MRO. Works around an issue on Jython where inspect.getmro will not return all base classes if multiple classes share the same name. Instead, this function will return a tuple containing the class itself, and the contents of cls.__bases__. See https://github.com/pypa/setuptools/issues/1024. """ if platform.python_implementation() == "Jython": return (cls,) + cls.__bases__ return inspect.getmro(cls)
Example #19
Source File: test_inspect.py From BinderFilter with MIT License | 5 votes |
def test_classic_mro(self): # Test classic-class method resolution order. class A: pass class B(A): pass class C(A): pass class D(B, C): pass expected = (D, B, A, C) got = inspect.getmro(D) self.assertEqual(expected, got)
Example #20
Source File: object_utils.py From nucleus7 with Mozilla Public License 2.0 | 5 votes |
def get_parent_method(cls: Optional[Callable] = None, method: Optional[Callable] = None ) -> Optional[List[Callable]]: """ Get the parent class if method is not specified otherwise get all parent methods which are overridden by method Parameters ---------- cls class to get the parents method method of the class to search for parents Returns ------- parent parent class or method """ if cls is None: return None parents = inspect.getmro(cls)[1:] if method is None: return list(parents) parent_methods = [getattr(cls, method.__name__) for cls in parents if hasattr(cls, method.__name__) and cls is not object] return parent_methods
Example #21
Source File: test_inspect.py From BinderFilter with MIT License | 5 votes |
def test_newstyle_mro(self): # The same w/ new-class MRO. class A(object): pass class B(A): pass class C(A): pass class D(B, C): pass expected = (D, B, C, A, object) got = inspect.getmro(D) self.assertEqual(expected, got)
Example #22
Source File: deprecation.py From bioforum with MIT License | 5 votes |
def __new__(cls, name, bases, attrs): new_class = super().__new__(cls, name, bases, attrs) for base in inspect.getmro(new_class): class_name = base.__name__ for renamed_method in cls.renamed_methods: old_method_name = renamed_method[0] old_method = base.__dict__.get(old_method_name) new_method_name = renamed_method[1] new_method = base.__dict__.get(new_method_name) deprecation_warning = renamed_method[2] wrapper = warn_about_renamed_method(class_name, *renamed_method) # Define the new method if missing and complain about it if not new_method and old_method: warnings.warn( "`%s.%s` method should be renamed `%s`." % (class_name, old_method_name, new_method_name), deprecation_warning, 2) setattr(base, new_method_name, old_method) setattr(base, old_method_name, wrapper(old_method)) # Define the old method as a wrapped call to the new method. if not old_method and new_method: setattr(base, old_method_name, wrapper(new_method)) return new_class
Example #23
Source File: parser.py From Yuki-Chan-The-Auto-Pentest with MIT License | 5 votes |
def getParserTags(cls): tags = {} for cls in reversed(getmro(cls)): if hasattr(cls, "PARSER_TAGS"): tags.update(cls.PARSER_TAGS) return tags
Example #24
Source File: __init__.py From FuYiSpider with Apache License 2.0 | 5 votes |
def _find_adapter(registry, ob): """Return an adapter factory for `ob` from `registry`""" types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob)))) for t in types: if t in registry: return registry[t]
Example #25
Source File: __init__.py From FuYiSpider with Apache License 2.0 | 5 votes |
def _find_adapter(registry, ob): """Return an adapter factory for `ob` from `registry`""" types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob)))) for t in types: if t in registry: return registry[t]
Example #26
Source File: base.py From scikit-multiflow with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _get_tags(self): collected_tags = {} for base_class in inspect.getmro(self.__class__): if (hasattr(base_class, '_more_tags') and base_class != self.__class__): more_tags = base_class._more_tags(self) collected_tags = _update_if_consistent(collected_tags, more_tags) if hasattr(self, '_more_tags'): more_tags = self._more_tags() collected_tags = _update_if_consistent(collected_tags, more_tags) tags = _DEFAULT_TAGS.copy() tags.update(collected_tags) return tags
Example #27
Source File: __init__.py From pkg_resources with MIT License | 5 votes |
def _find_adapter(registry, ob): """Return an adapter factory for `ob` from `registry`""" types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob)))) for t in types: if t in registry: return registry[t]
Example #28
Source File: query_utils.py From bioforum with MIT License | 5 votes |
def get_lookups(cls): class_lookups = [parent.__dict__.get('class_lookups', {}) for parent in inspect.getmro(cls)] return cls.merge_dicts(class_lookups)
Example #29
Source File: related.py From bioforum with MIT License | 5 votes |
def get_lookups(cls): bases = inspect.getmro(cls) bases = bases[:bases.index(ForeignObject) + 1] class_lookups = [parent.__dict__.get('class_lookups', {}) for parent in bases] return cls.merge_dicts(class_lookups)
Example #30
Source File: parser.py From ITWSV with MIT License | 5 votes |
def getParserTags(cls): tags = {} for cls in reversed(getmro(cls)): if hasattr(cls, "PARSER_TAGS"): tags.update(cls.PARSER_TAGS) return tags