當前位置: 首頁>>代碼示例>>Python>>正文


Python inspect.isabstract方法代碼示例

本文整理匯總了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)) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:24,代碼來源:test_inspect.py

示例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_ 
開發者ID:apache,項目名稱:airflow,代碼行數:21,代碼來源:test_core_to_contrib.py

示例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") 
開發者ID:yampelo,項目名稱:beagle,代碼行數:21,代碼來源:base_datasource.py

示例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)) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:23,代碼來源:test_inspect.py

示例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) 
開發者ID:runawayhorse001,項目名稱:LearningApacheSpark,代碼行數:27,代碼來源:tests.py

示例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 
開發者ID:cta-observatory,項目名稱:ctapipe,代碼行數:22,代碼來源:component.py

示例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 
開發者ID:zyfra,項目名稱:ebonite,代碼行數:23,代碼來源:base.py

示例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) 
開發者ID:CommvaultEngg,項目名稱:cvpysdk,代碼行數:20,代碼來源:vsinstance.py

示例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 
開發者ID:quantumlib,項目名稱:Cirq,代碼行數:22,代碼來源:json_serialization_test.py

示例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 
開發者ID:Ermlab,項目名稱:python-ddd,代碼行數:23,代碼來源:response.py

示例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) 
開發者ID:RasaHQ,項目名稱:rasa-sdk,代碼行數:18,代碼來源:executor.py

示例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 
開發者ID:asappresearch,項目名稱:flambe,代碼行數:25,代碼來源:registrable.py

示例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) 
開發者ID:asappresearch,項目名稱:flambe,代碼行數:22,代碼來源:component.py

示例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__() 
開發者ID:joaomgcd,項目名稱:VoiceAssistantWebHook,代碼行數:24,代碼來源:handlerutils.py

示例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() 
開發者ID:upura,項目名稱:ml-competition-template-titanic,代碼行數:7,代碼來源:base.py


注:本文中的inspect.isabstract方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。