Python inspect.isabstract() Examples
The following are 30
code examples of inspect.isabstract().
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: vsinstance.py From cvpysdk with Apache License 2.0 | 6 votes |
def __new__(cls, agent_object, instance_name, instance_id=None): """Decides which instance object needs to be created""" try: instance_name = VSINSTANCE_TYPE[agent_object.instances._vs_instance_type_dict[instance_id]] except KeyError: instance_name = re.sub('[^A-Za-z0-9_]+', '', instance_name.replace(" ", "_")) try: instance_module = import_module("cvpysdk.instances.virtualserver.{}".format(instance_name)) except ImportError: instance_module = import_module("cvpysdk.instances.virtualserver.null") classes = getmembers(instance_module, lambda m: isclass(m) and not isabstract(m)) for name, _class in classes: if issubclass(_class, VirtualServerInstance) and _class.__module__.rsplit(".", 1)[-1] == instance_name: return object.__new__(_class)
Example #2
Source File: handlerutils.py From VoiceAssistantWebHook with Apache License 2.0 | 6 votes |
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__()
Example #3
Source File: test_inspect.py From BinderFilter with MIT License | 6 votes |
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))
Example #4
Source File: test_inspect.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 6 votes |
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))
Example #5
Source File: test_inspect.py From oss-ftp with MIT License | 6 votes |
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))
Example #6
Source File: test_inspect.py From ironpython2 with Apache License 2.0 | 6 votes |
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))
Example #7
Source File: test_inspect.py From CTFCrackTools with GNU General Public License v3.0 | 6 votes |
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))
Example #8
Source File: test_inspect.py From CTFCrackTools-V2 with GNU General Public License v3.0 | 6 votes |
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))
Example #9
Source File: component.py From flambe with MIT License | 6 votes |
def from_yaml(cls: Type[C], constructor: Any, node: Any, factory_name: str) -> Schema: # Normally you would create an instance of this class with # cls(...) but in this case we don't want to init the object # yet so we create a modified schema that will recursively # initialize kwargs via compile when the top level compilation # begins if inspect.isabstract(cls): msg = f"You're trying to initialize an abstract class {cls}. " \ + "If you think it's concrete, double check you've spelled " \ + "all the method names correctly." raise Exception(msg) if isinstance(node, ScalarNode): nothing = constructor.construct_yaml_null(node) if nothing is not None: warn(f"Non-null scalar argument to {cls.__name__} will be ignored") return Schema(cls, _flambe_custom_factory_name=factory_name) # NOTE: construct_yaml_map is a generator that yields the # constructed data and then updates it kwargs, = list(constructor.construct_yaml_map(node)) return Schema(cls, _flambe_custom_factory_name=factory_name, **kwargs)
Example #10
Source File: test_core_to_contrib.py From airflow with Apache License 2.0 | 6 votes |
def get_class_from_path(path_to_class, parent=False): """ :param parent indicates if "path_to_class" arg is super class """ path, _, class_name = path_to_class.rpartition(".") module = importlib.import_module(path) class_ = getattr(module, class_name) if isabstract(class_) and not parent: class_name = f"Mock({class_.__name__})" attributes = { a: mock.MagicMock() for a in class_.__abstractmethods__ } new_class = type(class_name, (class_,), attributes) return new_class return class_
Example #11
Source File: registrable.py From flambe with MIT License | 6 votes |
def from_yaml(cls, constructor: Any, node: Any, factory_name: str) -> Any: """Use constructor to create an instance of cls""" if inspect.isabstract(cls): msg = f"You're trying to initialize an abstract class {cls.__name__}. " \ + "If you think it's concrete, double check you've spelled " \ + "all the originally abstract method names correctly." raise Exception(msg) if isinstance(node, ScalarNode): nothing = constructor.construct_yaml_null(node) if nothing is not None: warn(f"Non-null scalar argument to {cls.__name__} will be ignored. A map of kwargs" " should be used instead.") return cls() # NOTE: construct_yaml_map is a generator that yields the # constructed data and then updates it kwargs, = list(constructor.construct_yaml_map(node)) if factory_name is not None: factory_method = getattr(cls, factory_name) else: factory_method = cls instance = factory_method(**kwargs) instance._saved_kwargs = kwargs return instance
Example #12
Source File: base_datasource.py From beagle with MIT License | 6 votes |
def __init_subclass__(cls, **kwargs): """Validated the subclass has the required annotations. """ # Don't want this to trigger on abstract classes. if inspect.isabstract(cls): return if "name" not in cls.__dict__: raise RuntimeError(f"A DataSource sublcass **must** contain the name annotation") if "transformers" not in cls.__dict__: raise RuntimeError( f"A DataSource sublcass **must** contain the transformers annotation" ) if "category" not in cls.__dict__: raise RuntimeError(f"A DataSource sublcass **must** contain the category annotation") elif not isinstance(cls.transformers, list): raise RuntimeError(f"The tranformers annotation must be a list")
Example #13
Source File: test_inspect.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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))
Example #14
Source File: response.py From python-ddd with MIT License | 6 votes |
def default(self, obj): if isinstance(obj, datetime): return obj.isoformat() + 'Z' 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
Example #15
Source File: tests.py From LearningApacheSpark with MIT License | 6 votes |
def test_java_params(self): import pyspark.ml.feature import pyspark.ml.classification import pyspark.ml.clustering import pyspark.ml.evaluation import pyspark.ml.pipeline import pyspark.ml.recommendation import pyspark.ml.regression modules = [pyspark.ml.feature, pyspark.ml.classification, pyspark.ml.clustering, pyspark.ml.evaluation, 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 not name.endswith('Params')\ and issubclass(cls, JavaParams) and not inspect.isabstract(cls): # NOTE: disable check_params_exist until there is parity with Scala API ParamTests.check_params(self, cls(), check_params_exist=False) # Additional classes that need explicit construction from pyspark.ml.feature import CountVectorizerModel, StringIndexerModel ParamTests.check_params(self, CountVectorizerModel.from_vocabulary(['a'], 'input'), check_params_exist=False) ParamTests.check_params(self, StringIndexerModel.from_labels(['a', 'b'], 'input'), check_params_exist=False)
Example #16
Source File: test_inspect.py From ironpython3 with Apache License 2.0 | 6 votes |
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))
Example #17
Source File: component.py From ctapipe with BSD 3-Clause "New" or "Revised" License | 6 votes |
def non_abstract_children(base): """ Return all non-abstract subclasses of a base class recursively. Parameters ---------- base : class High level class object that is inherited by the desired subclasses Returns ------- non_abstract : dict dict of all non-abstract subclasses """ subclasses = base.__subclasses__() + [ g for s in base.__subclasses__() for g in non_abstract_children(s) ] non_abstract = [g for g in subclasses if not isabstract(g)] return non_abstract
Example #18
Source File: executor.py From rasa-sdk with Apache License 2.0 | 6 votes |
def _register_all_actions(self) -> None: """Scan for all user subclasses of `Action`, and register them. """ import inspect actions = utils.all_subclasses(Action) for action in actions: if ( not action.__module__.startswith("rasa_core.") and not action.__module__.startswith("rasa.") and not action.__module__.startswith("rasa_sdk.") and not action.__module__.startswith("rasa_core_sdk.") and not inspect.isabstract(action) ): self.register_action(action)
Example #19
Source File: test_inspect.py From gcblue with BSD 3-Clause "New" or "Revised" License | 6 votes |
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))
Example #20
Source File: json_serialization_test.py From Cirq with Apache License 2.0 | 6 votes |
def _get_all_public_classes(module) -> Iterator[Tuple[str, Type]]: for name, obj in inspect.getmembers(module): if inspect.isfunction(obj) or inspect.ismodule(obj): continue if name in SHOULDNT_BE_SERIALIZED: continue if not inspect.isclass(obj): # singletons, for instance obj = obj.__class__ if name.startswith('_'): continue if inspect.isclass(obj) and inspect.isabstract(obj): continue # assert name != 'XPowGate' yield name, obj
Example #21
Source File: base.py From ebonite with Apache License 2.0 | 6 votes |
def __init_subclass__(cls, **kwargs): if hasattr(cls, '__init__'): init = getattr(cls, '__init__') arg_spec = inspect.getfullargspec(init) if len(arg_spec.args) > 1: raise ValueError('Hook type [{}] cannot have __init__ with arguments'.format(cls.__name__)) if not inspect.isabstract(cls): for b in reversed(cls.__bases__): analyzer = getattr(b, ANALYZER_FIELD, None) if analyzer is not None: analyzer.hooks.append(cls()) logger.debug('Registering %s to %s', cls.__name__, analyzer.__name__) break else: raise ValueError( '{} defines process method, but dont have any parents with attached Analyzer'.format(cls)) super(Hook, cls).__init_subclass__(**kwargs) # noinspection PyAbstractClass
Example #22
Source File: test_abc.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
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))
Example #23
Source File: test_events.py From catalyst with Apache License 2.0 | 5 votes |
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)), )
Example #24
Source File: fitting.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __new__(mcls, name, bases, members): cls = super().__new__(mcls, name, bases, members) if not inspect.isabstract(cls) and not name.startswith('_'): mcls.registry.add(cls) return cls
Example #25
Source File: util.py From ansible-role-manager with Apache License 2.0 | 5 votes |
def find_subclasses(module, clazz): for name in dir(module): o = getattr(module, name) try: if (o != clazz) and issubclass(o, clazz) and not inspect.isabstract(o): yield name, o except TypeError: pass
Example #26
Source File: refleak.py From android_universal with MIT License | 5 votes |
def dash_R_cleanup(fs, ps, pic, zdc, abcs): import gc, copyreg import collections.abc # Restore some original values. warnings.filters[:] = fs copyreg.dispatch_table.clear() copyreg.dispatch_table.update(ps) sys.path_importer_cache.clear() sys.path_importer_cache.update(pic) try: import zipimport except ImportError: pass # Run unmodified on platforms without zipimport support else: zipimport._zip_directory_cache.clear() zipimport._zip_directory_cache.update(zdc) # clear type cache sys._clear_type_cache() # Clear ABC registries, restoring previously saved ABC registries. abs_classes = [getattr(collections.abc, a) for a in collections.abc.__all__] abs_classes = filter(isabstract, abs_classes) for abc in abs_classes: for obj in abc.__subclasses__() + [abc]: for ref in abcs.get(obj, set()): if ref() is not None: obj.register(ref()) obj._abc_caches_clear() clear_caches() # Collect cyclic trash and read memory statistics immediately after. func1 = sys.getallocatedblocks func2 = sys.gettotalrefcount gc.collect() return func1(), func2(), support.fd_count()
Example #27
Source File: test_abc.py From CTFCrackTools with GNU General Public License v3.0 | 5 votes |
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))
Example #28
Source File: vssubclient.py From cvpysdk with Apache License 2.0 | 5 votes |
def __new__(cls, backupset_object, subclient_name, subclient_id=None): """Decides which instance object needs to be created""" instance_name = backupset_object._instance_object.instance_name instance_name = re.sub('[^A-Za-z0-9_]+', '', instance_name.replace(" ", "_")) try: subclient_module = import_module("cvpysdk.subclients.virtualserver.{}".format(instance_name)) except ImportError: subclient_module = import_module("cvpysdk.subclients.virtualserver.null") classes = getmembers(subclient_module, lambda m: isclass(m) and not isabstract(m)) for name, _class in classes: if issubclass(_class, VirtualServerSubclient) and _class.__module__.rsplit(".", 1)[-1] == instance_name: return object.__new__(_class)
Example #29
Source File: test_abc.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
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))
Example #30
Source File: psd.py From pykernels with MIT License | 5 votes |
def testPSD(self): kernels = find_all_children(Kernel) for kernel, _ in kernels: if not inspect.isabstract(kernel): # ignore abstract classes for data in self.get_data(kernel): eigens, _ = la.eigh(kernel().gram(data)) self.assertTrue(np.all(eigens > -self.tol))