本文整理汇总了Python中inspect.isabstract方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.isabstract方法的具体用法?Python inspect.isabstract怎么用?Python inspect.isabstract使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类inspect
的用法示例。
在下文中一共展示了inspect.isabstract方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_isabstract
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isabstract [as 别名]
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))
示例2: get_class_from_path
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isabstract [as 别名]
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_
示例3: __init_subclass__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isabstract [as 别名]
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")
示例4: test_isabstract
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isabstract [as 别名]
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))
示例5: test_java_params
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isabstract [as 别名]
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)
示例6: non_abstract_children
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isabstract [as 别名]
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
示例7: __init_subclass__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isabstract [as 别名]
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
示例8: __new__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isabstract [as 别名]
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)
示例9: _get_all_public_classes
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isabstract [as 别名]
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
示例10: default
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isabstract [as 别名]
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
示例11: _register_all_actions
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isabstract [as 别名]
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)
示例12: from_yaml
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isabstract [as 别名]
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
示例13: from_yaml
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isabstract [as 别名]
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)
示例14: itersubclasses
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isabstract [as 别名]
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__()
示例15: get_features
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isabstract [as 别名]
def get_features(namespace):
for k, v in namespace.items():
if inspect.isclass(v) and issubclass(v, Feature) \
and not inspect.isabstract(v):
yield v()