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
python类isabstract()的实例源码
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 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 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 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 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 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 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 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 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 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 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 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 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 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 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))