我们从Python开源项目中,提取了以下42个代码示例,用于说明如何使用inspect.isabstract()。
def default(self, obj): if hasattr(obj, "to_json"): return self.default(obj.to_json()) elif hasattr(obj, "__dict__"): d = dict( (key, value) for key, value in inspect.getmembers(obj) if not key.startswith("__") and not inspect.isabstract(value) and not inspect.isbuiltin(value) and not inspect.isfunction(value) and not inspect.isgenerator(value) and not inspect.isgeneratorfunction(value) and not inspect.ismethod(value) and not inspect.ismethoddescriptor(value) and not inspect.isroutine(value) ) return self.default(d) return obj
def test_isabstract(self): from abc import ABCMeta, abstractmethod class AbstractClassExample(metaclass=ABCMeta): @abstractmethod def foo(self): pass class ClassExample(AbstractClassExample): def foo(self): pass a = ClassExample() # Test general behaviour. self.assertTrue(inspect.isabstract(AbstractClassExample)) self.assertFalse(inspect.isabstract(ClassExample)) self.assertFalse(inspect.isabstract(a)) self.assertFalse(inspect.isabstract(int)) self.assertFalse(inspect.isabstract(5))
def __init__(self, configpath): self.configpath = configpath # Find libraries inside the lib directory dir_path = os.path.join(os.path.dirname(__file__), "libraries") lib_files = [f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f)) and f.lower().endswith(".py") ] self.responses = [] self.libraries = [] for f in lib_files: # Try to load the module try: module_name = "hal.libraries." + f[:-3] module = importlib.import_module(module_name) for name, obj in inspect.getmembers(module): # Find classes that inherit from HalLibrary if inspect.isclass(obj) and issubclass(obj, HalLibrary) and \ name != "HalLibrary" and not inspect.isabstract(obj): self.libraries.append(obj) except: self.add_response("Error loading library {}".format(f)) raise
def test_isabstract(self): from abc import ABCMeta, abstractmethod class AbstractClassExample(object): __metaclass__ = ABCMeta @abstractmethod def foo(self): pass class ClassExample(AbstractClassExample): def foo(self): pass a = ClassExample() # Test general behaviour. self.assertTrue(inspect.isabstract(AbstractClassExample)) self.assertFalse(inspect.isabstract(ClassExample)) self.assertFalse(inspect.isabstract(a)) self.assertFalse(inspect.isabstract(int)) self.assertFalse(inspect.isabstract(5))
def default(self, obj): # if hasattr(obj, "to_json"): # return self.default(obj.to_json()) if isinstance(obj, Enum): return obj.name elif hasattr(obj, "__dict__"): d = dict( (key, value) for key, value in inspect.getmembers(obj) if not key.startswith("__") and not inspect.isabstract(value) and not inspect.isbuiltin(value) and not inspect.isfunction(value) and not inspect.isgenerator(value) and not inspect.isgeneratorfunction(value) and not inspect.ismethod(value) and not inspect.ismethoddescriptor(value) and not inspect.isroutine(value) and not self.isempty(value) and not value is None ) return self.default(d) return obj
def itersubclasses(cls, _seen=None): if not isinstance(cls, type): raise TypeError('itersubclasses must be called with ' 'new-style classes, not %.100r' % cls) if _seen is None: _seen = set() try: subs = cls.__subclasses__() except TypeError: # fails only when cls is type subs = cls.__subclasses__(cls) for sub in subs: isAbstract = inspect.isabstract(sub) #print str(sub) + "is abstract: " + str(isAbstract) if sub not in _seen: _seen.add(sub) if not isAbstract: print "Loading Handler: " + str(sub) yield sub for sub in itersubclasses(sub, _seen): yield sub #assistanHandlerClasses = vars()['AssistantHandler'].__subclasses__()
def default(self, obj): if hasattr(obj, "to_json"): return self.default(obj.to_json()) elif hasattr(obj, "__dict__"): data = dict( (key, value) for key, value in inspect.getmembers(obj) if not key.startswith("__") and not inspect.isabstract(value) and not inspect.isbuiltin(value) and not inspect.isfunction(value) and not inspect.isgenerator(value) and not inspect.isgeneratorfunction(value) and not inspect.ismethod(value) and not inspect.ismethoddescriptor(value) and not inspect.isroutine(value) ) return self.default(data) return obj
def _discover_renderers(self): infos = OrderedDict() for ep_mod in iter_entry_points(group='uchroma.plugins', name='renderers'): obj = ep_mod.load() if not inspect.ismodule(obj): self._logger.error("Plugin %s is not a module, skipping", ep_mod) continue for ep_cls in iter_entry_points(group='uchroma.plugins', name='renderer'): obj = ep_cls.load() if not issubclass(obj, Renderer): self._logger.error("Plugin %s is not a renderer, skipping", ep_cls) continue for obj in Renderer.__subclasses__(): if inspect.isabstract(obj): continue if obj.meta.display_name == '_unknown_': self._logger.error("Renderer %s did not set metadata, skipping", obj.__name__) continue key = '%s.%s' % (obj.__module__, obj.__name__) infos[key] = RendererInfo(obj.__module__, obj, key, obj.meta, obj.class_traits()) self._logger.debug("Loaded renderers: %s", ', '.join(infos.keys())) return infos
def optimizations(cls): """ :return: """ if not hasattr(cls, '_optimizations'): cls._optimizations = {} package = sys.modules[BasicOptimization.__module__] path = os.path.dirname(package.__file__) for loader, module_name, is_pkg in pkgutil.iter_modules([path]): if module_name.startswith('__'): continue module = import_module('.' + module_name, package.__name__) for _type in vars(module).values(): if not isinstance(_type, type): continue if isabstract(_type): continue if not issubclass(_type, cls): continue try: obj = _type() cls._optimizations[obj.id] = obj except: pass return cls._optimizations
def test_java_params(self): import pyspark.ml.feature import pyspark.ml.classification import pyspark.ml.clustering import pyspark.ml.pipeline import pyspark.ml.recommendation import pyspark.ml.regression modules = [pyspark.ml.feature, pyspark.ml.classification, pyspark.ml.clustering, pyspark.ml.pipeline, pyspark.ml.recommendation, pyspark.ml.regression] for module in modules: for name, cls in inspect.getmembers(module, inspect.isclass): if not name.endswith('Model') and issubclass(cls, JavaParams)\ and not inspect.isabstract(cls): self.check_params(cls())
def test_completeness(self): """ Tests that all rules are being tested. """ if not self.class_: return # This is the base class testing, it is always complete. classes_to_ignore = [TradingDayOfWeekRule, TradingDayOfMonthRule] dem = { k for k, v in iteritems(vars(catalyst.utils.events)) if isinstance(v, type) and issubclass(v, self.class_) and v is not self.class_ and v not in classes_to_ignore and not isabstract(v) } ds = { k[5:] for k in dir(self) if k.startswith('test') and k[5:] in dem } self.assertTrue( dem <= ds, msg='This suite is missing tests for the following classes:\n' + '\n'.join(map(repr, dem - ds)), )
def _get_instances(module, instance_type): result = {} module_dict = module.__dict__ if "__all__" in module_dict: module_name = module_dict["__name__"] sub_modules_names = module_dict["__all__"] for sub_module_name_it in sub_modules_names: sub_module_complete_name = module_name + "." + sub_module_name_it try: sub_module_it = __import__(sub_module_complete_name, fromlist = ["*"]) except Exception as ex: # Can be ImportError, but also TabError, and more. logging.warning('Error importing local command %s: %s', sub_module_complete_name, ex) continue sub_instances = _get_instances(sub_module_it, instance_type) for (klass, instance) in sub_instances.items(): result[klass] = instance module_attributes = dir(module) for attribute_name in module_attributes: attribute_value = getattr(module, attribute_name) is_valid = attribute_value != instance_type is_valid = is_valid and inspect.isclass(attribute_value) is_valid = is_valid and issubclass(attribute_value, instance_type) is_valid = is_valid and not inspect.isabstract(attribute_value) if is_valid: result[attribute_value.__name__] = attribute_value() return result
def test_abstractmethod_integration(self): for abstractthing in [abc.abstractmethod, abc.abstractproperty, abc.abstractclassmethod, abc.abstractstaticmethod]: class C(metaclass=abc.ABCMeta): @abstractthing def foo(self): pass # abstract def bar(self): pass # concrete self.assertEqual(C.__abstractmethods__, {"foo"}) self.assertRaises(TypeError, C) # because foo is abstract self.assertTrue(isabstract(C)) class D(C): def bar(self): pass # concrete override of concrete self.assertEqual(D.__abstractmethods__, {"foo"}) self.assertRaises(TypeError, D) # because foo is still abstract self.assertTrue(isabstract(D)) class E(D): def foo(self): pass self.assertEqual(E.__abstractmethods__, set()) E() # now foo is concrete, too self.assertFalse(isabstract(E)) class F(E): @abstractthing def bar(self): pass # abstract override of concrete self.assertEqual(F.__abstractmethods__, {"bar"}) self.assertRaises(TypeError, F) # because bar is abstract now self.assertTrue(isabstract(F))
def test_abstractmethod_integration(self): for abstractthing in [abc.abstractmethod, abc.abstractproperty]: class C: __metaclass__ = abc.ABCMeta @abstractthing def foo(self): pass # abstract def bar(self): pass # concrete self.assertEqual(C.__abstractmethods__, set(["foo"])) self.assertRaises(TypeError, C) # because foo is abstract self.assertTrue(isabstract(C)) class D(C): def bar(self): pass # concrete override of concrete self.assertEqual(D.__abstractmethods__, set(["foo"])) self.assertRaises(TypeError, D) # because foo is still abstract self.assertTrue(isabstract(D)) class E(D): def foo(self): pass self.assertEqual(E.__abstractmethods__, set()) E() # now foo is concrete, too self.assertFalse(isabstract(E)) class F(E): @abstractthing def bar(self): pass # abstract override of concrete self.assertEqual(F.__abstractmethods__, set(["bar"])) self.assertRaises(TypeError, F) # because bar is abstract now self.assertTrue(isabstract(F))
def get_available_inherited_classes(pkg, base_class): """Gets all inherited classes in modules for a given package This does not include subpackages. :type pkg: str :param pkg: a package name. :type base_class: object :param base_class: a base class. :rtype: list :returns: a list of inherited classes. """ available_classes = [] pkg_path = os.path.dirname(pkg.__file__) for _, mod_name, _ in pkgutil.iter_modules([pkg_path]): if not mod_name.startswith("_"): try: module = importlib.import_module("{0}.{1}".format(pkg.__name__, mod_name)) for clazz in inspect.getmembers(module, inspect.isclass): if clazz is not base_class: if issubclass(clazz[1], base_class) and\ not inspect.isabstract(clazz[1]) and\ clazz[1] != base_class: available_classes.append(clazz[1]) except Exception as e: logger.warn(e.__str__()) return set(available_classes)
def __init__(cls, what, bases=None, dict=None): super(AdapterMeta, cls).__init__(what, bases, dict) if not is_abstract(cls): for protocol in getattr(cls, 'supported_protocols', ()): # Note that we will not overwrite existing registered adapters. adapter_registry.setdefault(protocol, cls)
def map_modules(obj, parent): """ Find and map all the modules recursively. :param obj: Find all modules from the object. :type obj: :class:`object` :param parent: Parent node which you are searching in. :type parent: :class:`ruruki.interfaces.IVertex` """ # get all the functions in the module for _, obj in inspect.getmembers(obj, inspect.ismodule): _id = id(obj) + id(parent) if _id in SEEN: continue SEEN.add(_id) node = GRAPH.get_or_create_vertex("module", name=obj.__name__) node.set_property(abstract=inspect.isabstract(obj)) GRAPH.get_or_create_edge(parent, "imports", node) map_filename(obj, node) logging.debug( "(%s)-[:imports]->(%s)", parent.properties["name"], obj.__name__ ) map_classes(obj, node) map_functions(obj, node) map_modules(obj, node)
def test_class_abstraction(self): """Test if the class is an abstract class""" assert inspect.isabstract(self.klass)
def is_abstract(cls): ABCFLAG = '__abstractmethods__' isabc = hasattr(cls, ABCFLAG) or inspect.isabstract(cls) return isabc
def get_subclasses(class_type, directory=None): """ Creates a dictionary of classes which inherit from ``class_type`` found in all python files within a given directory, keyed by the class name in snake case as a string. :param class_type: The base class that all returned classes should inherit from. :type class_type: cls :param directory: The directory to look for classes in. :type directory: str :returns: A dict of classes found. :rtype: dict """ try: glob_expression = os.path.join(directory, "*.py") except (AttributeError, TypeError): raise TypeError("'directory' object should be a string") module_paths = glob.glob(glob_expression) sys.path.append(directory) modules = [ imp.load_source( os.path.basename(module_path).split(".")[0], module_path ) for module_path in module_paths if "__init__" not in module_path ] classes = {} for module in modules: for attr in module.__dict__.values(): if inspect.isclass(attr) \ and issubclass(attr, class_type) \ and not inspect.isabstract(attr): classes[camel_to_snake_case(attr.__name__)] = attr return classes
def is_class(klass): return inspect.isclass(klass) and (not inspect.isabstract(klass))
def register_module(self, module, overwrite=False): """ Register all component classes within a module. Parameters ---------- module : Union[str, `ModuleType`] overwrite : bool """ if isinstance(module, basestring): module = pydoc.locate(module) if not inspect.ismodule(module): raise ValueError('module must be either a module or the name of a ' 'module') self.logger.info('Registering components in module: {}'.format( module.__name__)) registered = 0 for obj_name, class_obj in inspect.getmembers(module): if (inspect.isclass(class_obj) and class_obj is not Component and not inspect.isabstract(class_obj) and not issubclass(class_obj, SubGraph) and issubclass(class_obj, Component)): self.register_component(class_obj, overwrite) registered += 1 if registered == 0: self.logger.warn('No components were found in module: {}'.format( module.__name__))
def _execute_backend_on_spec(self): """Renders a source file into its final form.""" api_no_aliases_cache = None for attr_key in dir(self.backend_module): attr_value = getattr(self.backend_module, attr_key) if (inspect.isclass(attr_value) and issubclass(attr_value, Backend) and not inspect.isabstract(attr_value)): self._logger.info('Running backend: %s', attr_value.__name__) backend = attr_value(self.build_path, self.backend_args) if backend.preserve_aliases: api = self.api else: if not api_no_aliases_cache: api_no_aliases_cache = remove_aliases_from_api(self.api) api = api_no_aliases_cache try: backend.generate(api) except Exception: # Wrap this exception so that it isn't thought of as a bug # in the stone parser, but rather a bug in the backend. # Remove the last char of the traceback b/c it's a newline. raise BackendException( attr_value.__name__, traceback.format_exc()[:-1])
def _loader(self, cls: type): # Forces unittest.TestLoader to return tests from abstract base classes as None. if isabstract(cls): return None else: return self.unpatched_loadTestsFromTestCase(cls)
def prefetch(session, discussion_id): from assembl.lib.sqla import class_registry from assembl.models import DiscussionBoundBase for name, cls in class_registry.items(): if issubclass(cls, DiscussionBoundBase) and not isabstract(cls): mapper = class_mapper(cls) undefers = [undefer(attr.key) for attr in mapper.iterate_properties if getattr(attr, 'deferred', False)] conditions = cls.get_discussion_conditions(discussion_id) session.query(with_polymorphic(cls, "*")).filter( and_(*conditions)).options(*undefers).all()
def get_concrete_subclasses_recursive(c): """Recursively returns only the concrete classes is a class hierarchy""" concreteSubclasses = [] subclasses = get_subclasses_recursive(c) for d in subclasses: if not inspect.isabstract(d): concreteSubclasses.append(d) return concreteSubclasses
def get_base_conditions(self, alias_maker, cls, for_graph): from ..models import DiscussionBoundBase conditions = super( AssemblClassPatternExtractor, self).get_base_conditions( alias_maker, cls, for_graph) base_conds = cls.base_conditions(alias_maker=alias_maker) if base_conds: conditions.extend(base_conds) if (for_graph.discussion_id and issubclass(cls, DiscussionBoundBase) and not isabstract(cls)): # TODO: update with conditionS. conditions.extend(cls.get_discussion_conditions( for_graph.discussion_id, alias_maker)) return [c for c in conditions if c is not None]
def delete_discussion(session, discussion_id): from assembl.models import ( Base, Discussion, DiscussionBoundBase, Preferences, LangStringEntry) # delete anything related first classes = DiscussionBoundBase._decl_class_registry.values() classes_by_table = defaultdict(list) for cls in classes: if isinstance(cls, type): classes_by_table[getattr(cls, '__table__', None)].append(cls) # Only direct subclass of abstract def is_concrete_class(cls): if isabstract(cls): return False for (i, cls) in enumerate(cls.mro()): if not i: continue if not issubclass(cls, Base): continue return isabstract(cls) concrete_classes = set([cls for cls in itertools.chain( *list(classes_by_table.values())) if issubclass(cls, DiscussionBoundBase) and is_concrete_class(cls)]) concrete_classes.add(Preferences) concrete_classes.add(LangStringEntry) tables = DiscussionBoundBase.metadata.sorted_tables # Special case for preferences discussion = session.query(Discussion).get(discussion_id) session.delete(discussion.preferences) # tables.append(Preferences.__table__) tables.reverse() for table in tables: if table not in classes_by_table: continue for cls in classes_by_table[table]: if cls not in concrete_classes: continue print('deleting', cls.__name__) query = session.query(cls.id) if hasattr(cls, "get_discussion_conditions"): conds = cls.get_discussion_conditions(discussion_id) else: continue assert conds cond = and_(*conds) v = JoinColumnsVisitor(cls, query, classes_by_table) v.traverse(cond) query = v.final_query().filter(cond) if query.count(): print("*" * 20, "Not all deleted!") ids = query.all() for subcls in cls.mro(): if getattr(subcls, '__tablename__', None): session.query(subcls).filter( subcls.id.in_(ids)).delete(False) session.flush()