def get_action(driver, keyword):
"""get action class corresponding to the keyword in the driver
"""
drvmod = 'ProductDrivers.' + driver
drvmodobj = importlib.import_module(drvmod)
drvfile_methods = inspect.getmembers(drvmodobj, inspect.isroutine)
main_method = [item[1] for item in drvfile_methods if item[0] == 'main'][0]
main_src = inspect.getsource(main_method)
pkglstmatch = re.search(r'package_list.*=.*\[(.*)\]', main_src, re.MULTILINE | re.DOTALL)
pkglst = pkglstmatch.group(1).split(',')
for pkg in pkglst:
pkgobj = importlib.import_module(pkg)
pkgdir = os.path.dirname(pkgobj.__file__)
action_modules = [pkg+'.'+name for _, name, _ in pkgutil.iter_modules([pkgdir])]
action_module_objs = [importlib.import_module(action_module) for action_module in action_modules]
for action_module_obj in action_module_objs:
for action_class in inspect.getmembers(action_module_obj, inspect.isclass):
for func_name in inspect.getmembers(action_class[1], inspect.isroutine):
if keyword == func_name[0]:
return action_class[1]
return None
python类isclass()的实例源码
def get_containing_module(value):
"""
Return the name of the module containing the given value, or
C{None} if the module name can't be determined.
@rtype: L{DottedName}
"""
if inspect.ismodule(value):
return DottedName(value.__name__)
elif isclass(value):
return DottedName(value.__module__)
elif (inspect.ismethod(value) and value.im_self is not None and
value.im_class is ClassType): # class method.
return DottedName(value.im_self.__module__)
elif inspect.ismethod(value):
return DottedName(value.im_class.__module__)
elif inspect.isroutine(value):
module = _find_function_module(value)
if module is None: return None
return DottedName(module)
else:
return None
def __init__(self, type_list):
mod_name = sys.modules[__name__]
cls_list = [
cls[0]
for cls in inspect.getmembers(mod_name)
if cls[0].isupper() and inspect.isclass(cls[1]) and cls[1].__module__ == __name__
]
try:
type_list.remove('TERMINATE') # can't hold order, so remove it and add it back when done
except ValueError as exc:
pass
type_list = list(set(type_list).intersection(set(cls_list))) # remove bad and duplicate values
array_args = [
{'version': getattr(getattr(mod_name, rtype), 'version'),
'code': getattr(getattr(mod_name, rtype), 'code')}
for rtype in type_list
]
array_args.append({'code': 0, 'version': 0}) # add TERMINATE as last req
self.streaming_event_request = StreamingEventRequest(service_array=array_args, timestamp=Struct.get_ts(), flags=Struct.get_flags())
self.message_header = MessageHeader(type=2049, data=self.streaming_event_request)
self.record = self.message_header.pack()
def get_plugs_mail_classes(self, app):
"""
Returns a list of tuples, but it should
return a list of dicts
"""
classes = []
members = self.get_members(app)
for member in members:
name, cls = member
if inspect.isclass(cls) and issubclass(cls, PlugsMail) and name != 'PlugsMail':
files_ = self.get_template_files(app.__file__, name)
for file_ in files_:
try:
description = cls.description
location = file_
language = self.get_template_language(location)
classes.append((name, location, description, language))
except AttributeError:
raise AttributeError('Email class must specify email description.')
return classes
def document(self, object, name=None, *args):
"""Generate documentation for an object."""
args = (object, name) + args
# 'try' clause is to attempt to handle the possibility that inspect
# identifies something in a way that pydoc itself has issues handling;
# think 'super' and how it is a descriptor (which raises the exception
# by lacking a __name__ attribute) and an instance.
if inspect.isgetsetdescriptor(object): return self.docdata(*args)
if inspect.ismemberdescriptor(object): return self.docdata(*args)
try:
if inspect.ismodule(object): return self.docmodule(*args)
if inspect.isclass(object): return self.docclass(*args)
if inspect.isroutine(object): return self.docroutine(*args)
except AttributeError:
pass
if isinstance(object, property): return self.docproperty(*args)
return self.docother(*args)
def render_doc(thing, title='Python Library Documentation: %s', forceload=0):
"""Render text documentation, given an object or a path to an object."""
object, name = resolve(thing, forceload)
desc = describe(object)
module = inspect.getmodule(object)
if name and '.' in name:
desc += ' in ' + name[:name.rfind('.')]
elif module and module is not object:
desc += ' in module ' + module.__name__
if type(object) is _OLD_INSTANCE_TYPE:
# If the passed object is an instance of an old-style class,
# document its available methods instead of its value.
object = object.__class__
elif not (inspect.ismodule(object) or
inspect.isclass(object) or
inspect.isroutine(object) or
inspect.isgetsetdescriptor(object) or
inspect.ismemberdescriptor(object) or
isinstance(object, property)):
# If the passed object is a piece of data or an instance,
# document its available methods instead of its value.
object = type(object)
desc += ' object'
return title % desc + '\n\n' + text.document(object, name)
def _from_module(self, module, object):
"""
Return true if the given object is defined in the given
module.
"""
if module is None:
return True
elif inspect.isfunction(object):
return module.__dict__ is object.func_globals
elif inspect.isclass(object):
return module.__name__ == object.__module__
elif inspect.getmodule(object) is not None:
return module is inspect.getmodule(object)
elif hasattr(object, '__module__'):
return module.__name__ == object.__module__
elif isinstance(object, property):
return True # [XX] no way not be sure.
else:
raise ValueError("object must be a class or function")
def _from_module(self, module, object):
"""
Return true if the given object is defined in the given
module.
"""
if module is None:
return True
elif inspect.isfunction(object):
return module.__dict__ is func_globals(object)
elif inspect.isclass(object):
return module.__name__ == object.__module__
elif inspect.getmodule(object) is not None:
return module is inspect.getmodule(object)
elif hasattr(object, '__module__'):
return module.__name__ == object.__module__
elif isinstance(object, property):
return True # [XX] no way not be sure.
else:
raise ValueError("object must be a class or function")
def __new__(cls, name, bases, attrs):
new_class = super(AliasType, cls).__new__(cls, name, bases, attrs)
# see whether we've got an Alias inner class:
if inspect.isclass(attrs.get('Alias', None)):
alias = attrs['Alias']
setattr(new_class, '__aliases', {})
for attr, value in alias.__dict__.items():
# don't want any "private" attrs appearing
if attr.startswith('_'):
continue
# don't care if these aren't tuples or lists
if not isinstance(value, (tuple, list)):
continue
# no point in setting up an alias for something which isn't a
# class attribute:
if not attr in attrs:
continue
# if we've got to here put the lookups into the __aliases dict:
for key in value:
new_class.__dict__['__aliases'][key] = attr
setattr(new_class, key, AliasDescriptor(key))
return new_class
def describe(module):
""" Describe the module object passed as argument
including its classes and functions """
wi('[Module: %s]\n' % module.__name__)
indent()
count = 0
for name in dir(module):
obj = getattr(module, name)
if inspect.isclass(obj):
count += 1; describe_klass(obj)
elif (inspect.ismethod(obj) or inspect.isfunction(obj)):
count +=1 ; describe_func(obj)
elif inspect.isbuiltin(obj):
count += 1; describe_builtin(obj)
if count==0:
wi('(No members)')
dedent()
def init_db():
"""
Import all modules here that might define models so that
they will be registered properly on the metadata, and then
create a database
"""
def func(subcls):
""" To check the subclasses of BASE"""
try:
if issubclass(subcls[1], BASE):
return True
except TypeError:
pass
return False
# pylint: disable=bad-builtin
subclses = filter(func, inspect.getmembers(models, inspect.isclass))
LOGGER.debug('Import models: %s', [subcls[1] for subcls in subclses])
BASE.metadata.create_all(bind=ENGINE)
def register_check(check, codes=None):
"""Register a new check object."""
def _add_check(check, kind, codes, args):
if check in _checks[kind]:
_checks[kind][check][0].extend(codes or [])
else:
_checks[kind][check] = (codes or [''], args)
if inspect.isfunction(check):
args = _get_parameters(check)
if args and args[0] in ('physical_line', 'logical_line'):
if codes is None:
codes = ERRORCODE_REGEX.findall(check.__doc__ or '')
_add_check(check, args[0], codes, args)
elif inspect.isclass(check):
if _get_parameters(check.__init__)[:2] == ['self', 'tree']:
_add_check(check, 'tree', codes, None)
def activation_str(self):
"""
Get printable string from activation function.
:return: string
"""
if hasattr(self, 'activation'):
if self.activation is None:
return str(None)
elif inspect.isclass(self.activation):
return self.activation.__class__.__name__
elif inspect.isfunction(self.activation):
return self.activation.__name__
else:
return str(self.activation)
else:
return ''
def load_skill_class(self, folder_name):
cls_name = to_camel(folder_name)
skill_name = folder_name.replace(self._suffix, '')
if skill_name in self._classes:
self.rt.intent.remove_skill(skill_name)
try:
mod = import_module(folder_name + '.skill')
mod = reload(mod)
cls = getattr(mod, cls_name, '')
except:
log.exception('Loading', folder_name)
return None
if not isclass(cls):
log.warning('Could not find', cls_name, 'in', folder_name)
return None
return cls
def load_class(self, option):
package = self._package + '.' + option + self._suffix
try:
mod = import_module(package)
cls = getattr(mod, to_camel(option + self._suffix), '')
if not isclass(cls):
log.error('Class not callable:', cls)
else:
if hasattr(self, 'plugin_path'):
plugin_path = self.plugin_path + '.'
else:
plugin_path = ''
cls.attr_name = self.make_name(cls)
cls.plugin_path = plugin_path + cls.attr_name
return cls
except:
log.exception('Loading Module', package)
return None
def _registered(self, cls):
if inspect.isclass(cls) and issubclass(cls, self._registerable_class):
found = self._registry.get(cls, None)
if found:
return found
else:
# Allow for fetching by slugs as well.
for registered in self._registry.values():
if registered.slug == cls:
return registered
class_name = self._registerable_class.__name__
if hasattr(self, "_registered_with"):
parent = self._registered_with._registerable_class.__name__
raise NotRegistered('%(type)s with slug "%(slug)s" is not '
'registered with %(parent)s "%(name)s".'
% {"type": class_name,
"slug": cls,
"parent": parent,
"name": self.slug})
else:
slug = getattr(cls, "slug", cls)
raise NotRegistered('%(type)s with slug "%(slug)s" is not '
'registered.' % {"type": class_name,
"slug": slug})
def registerByPackage(self, pkg):
"""This function is similar to registerByModule() but works on packages, this is an expensive operation as it
requires a recursive search by importing all sub modules and and searching them.
:param pkg: The package path to register eg. zoo.libs.apps
:type pkg: str
"""
mod = modules.importModule(pkg)
realPath = os.path.dirname(inspect.getfile(mod))
pkgSplitPath = pkg.replace(".", os.path.sep)
self.basePaths.append(realPath)
for subModule in modules.iterModules(realPath):
filename = os.path.splitext(os.path.basename(subModule))[0]
if filename.startswith("__") or subModule.endswith(".pyc"):
continue
newDottedPath = pkg + subModule.split(pkgSplitPath)[-1].replace(os.path.sep, ".").split(".py")[0]
subModuleObj = modules.importModule(newDottedPath)
for member in modules.iterMembers(subModuleObj, predicate=inspect.isclass):
self.registerPlugin(member[1])
def registerByPackage( pkg):
"""This function is similar to registerByModule() but works on packages, this is an expensive operation as it
requires a recursive search by importing all sub modules and and searching them.
:param pkg: The package path to register eg. zoo.libs.apps
:type pkg: str
"""
visited = set()
commands = []
for subModule in modules.iterModules(pkg):
filename = os.path.splitext(os.path.basename(subModule))[0]
if filename.startswith("__") or subModule.endswith(".pyc") or filename in visited:
continue
visited.add(filename)
subModuleObj = modules.importModule(subModule)
for member in modules.iterMembers(subModuleObj, predicate=inspect.isclass):
newCom = registerCommand(member[1])
if newCom:
commands.append(newCom)
return commands
def apply(self):
"""
Applies all extensions and hooks to this phase.
"""
def apply_extensions(extensions):
for extension in extensions:
verify_type_or_subclass(extension, Extension)
if isclass(extension):
extension = extension()
extension.apply_to_phase(self)
apply_extensions(extension.extensions)
apply_extensions(self.extensions)
for hook in self.hooks:
hook(self)
def command_as_str(self, argument_filter=None):
"""
Applies all extensions to the executor and calls its ``command_as_str``.
:returns: command as string
:rtype: basestring
"""
def apply_extensions(extensions):
for extension in extensions:
verify_type_or_subclass(extension, Extension)
if isclass(extension):
extension = extension()
extension.apply_to_executor(self.executor)
apply_extensions(extension.extensions)
apply_extensions(self.extensions)
return self.executor.command_as_str(argument_filter)
def verify_type(value, the_type):
"""
Raises :class:`TypeError` if the value is not an instance of the type.
:param value: value
:param the_type: type or type name
:type the_type: type|basestring
:raises TypeError: if ``value`` is not an instance of ``the_type``
:raises ~exceptions.ValueError: if ``the_type`` is invalid
:raises ImportError: if could not import the module
:raises AttributeError: if could not find the symbol in the module
"""
if isinstance(the_type, basestring):
the_type = import_symbol(the_type)
if not isclass(the_type):
raise ValueError(u'{} is not a type'.format(the_type))
if not isinstance(value, the_type):
raise TypeError(u'not an instance of {}: {}'.format(type_name(the_type),
type_name(type(value))))
def verify_subclass(value, the_type):
"""
Raises :class:`TypeError` if the value is not a subclass of the type.
:param value: value
:param the_type: type or type name
:type the_type: type|basestring
:raises TypeError: if ``value`` is not a subclass of ``the_type``
:raises ~exceptions.ValueError: if ``the_type`` is invalid
:raises ImportError: if could not import the module
:raises AttributeError: if could not find the symbol in the module
"""
if isinstance(the_type, basestring):
the_type = import_symbol(the_type)
if not isclass(the_type):
raise ValueError(u'{} is not a type'.format(the_type))
if not issubclass(value, the_type):
raise TypeError(u'not a subclass of {}: {}'.format(type_name(the_type),
type_name(type(value))))
def get_decorators(cls):
decorators = {}
def visit_FunctionDef(node):
decorators[node.name] = []
for n in node.decorator_list:
name = ''
if isinstance(n, ast.Call):
name = n.func.attr if isinstance(n.func, ast.Attribute) else n.func.id
else:
name = n.attr if isinstance(n, ast.Attribute) else n.id
args = [a.s for a in n.args] if hasattr(n, 'args') else []
decorators[node.name].append((name, args))
node_iter = ast.NodeVisitor()
node_iter.visit_FunctionDef = visit_FunctionDef
_cls = cls if inspect.isclass(cls) else cls.__class__
node_iter.visit(ast.parse(inspect.getsource(_cls)))
return decorators
def test_resources(self):
"""Create all the resources to test model definition"""
try:
model_list = []
for _, model_class in inspect.getmembers(models):
if inspect.isclass(model_class) and (
issubclass(model_class, core.ModelBase)):
model_list.append(model_class)
for model_class in _sort_model_by_foreign_key(model_list):
create_dict = _construct_resource_dict(model_class)
with self.context.session.begin():
core.create_resource(
self.context, model_class, create_dict)
except Exception as e:
msg = str(e)
self.fail('test_resources raised Exception unexpectedly %s' % msg)
def join(self, dest, join_type=None, on=None):
src = self._query_ctx
if on is None:
require_join_condition = join_type != JOIN.CROSS and (
isinstance(dest, SelectQuery) or
(isclass(dest) and not src._meta.rel_exists(dest)))
if require_join_condition:
raise ValueError('A join condition must be specified.')
elif join_type == JOIN.CROSS:
raise ValueError('A CROSS join cannot have a constraint.')
elif isinstance(on, basestring):
on = src._meta.fields[on]
self._joins.setdefault(src, [])
self._joins[src].append(Join(src, dest, join_type, on))
if not isinstance(dest, SelectQuery):
self._query_ctx = dest
def _from_module(self, module, object):
"""
Return true if the given object is defined in the given
module.
"""
if module is None:
return True
elif inspect.isfunction(object):
return module.__dict__ is object.func_globals
elif inspect.isclass(object):
# Some jython classes don't set __module__
return module.__name__ == getattr(object, '__module__', None)
elif inspect.getmodule(object) is not None:
return module is inspect.getmodule(object)
elif hasattr(object, '__module__'):
return module.__name__ == object.__module__
elif isinstance(object, property):
return True # [XX] no way not be sure.
else:
raise ValueError("object must be a class or function")
def document(self, object, name=None, *args):
"""Generate documentation for an object."""
args = (object, name) + args
# 'try' clause is to attempt to handle the possibility that inspect
# identifies something in a way that pydoc itself has issues handling;
# think 'super' and how it is a descriptor (which raises the exception
# by lacking a __name__ attribute) and an instance.
if inspect.isgetsetdescriptor(object): return self.docdata(*args)
if inspect.ismemberdescriptor(object): return self.docdata(*args)
try:
if inspect.ismodule(object): return self.docmodule(*args)
if inspect.isclass(object): return self.docclass(*args)
if inspect.isroutine(object): return self.docroutine(*args)
except AttributeError:
pass
if isinstance(object, property): return self.docproperty(*args)
return self.docother(*args)
def render_doc(thing, title='Python Library Documentation: %s', forceload=0):
"""Render text documentation, given an object or a path to an object."""
object, name = resolve(thing, forceload)
desc = describe(object)
module = inspect.getmodule(object)
if name and '.' in name:
desc += ' in ' + name[:name.rfind('.')]
elif module and module is not object:
desc += ' in module ' + module.__name__
if type(object) is _OLD_INSTANCE_TYPE:
# If the passed object is an instance of an old-style class,
# document its available methods instead of its value.
object = object.__class__
elif not (inspect.ismodule(object) or
inspect.isclass(object) or
inspect.isroutine(object) or
inspect.isgetsetdescriptor(object) or
inspect.ismemberdescriptor(object) or
isinstance(object, property)):
# If the passed object is a piece of data or an instance,
# document its available methods instead of its value.
object = type(object)
desc += ' object'
return title % desc + '\n\n' + text.document(object, name)
def _from_module(self, module, object):
"""
Return true if the given object is defined in the given
module.
"""
if module is None:
return True
elif inspect.getmodule(object) is not None:
return module is inspect.getmodule(object)
elif inspect.isfunction(object):
return module.__dict__ is object.func_globals
elif inspect.isclass(object):
return module.__name__ == object.__module__
elif hasattr(object, '__module__'):
return module.__name__ == object.__module__
elif isinstance(object, property):
return True # [XX] no way not be sure.
else:
raise ValueError("object must be a class or function")
def __init__(self, base=ServiceSOAPBinding, prefix='soap',
service_class=SOAPService):
'''
parameters:
base -- either a class definition, or a str representing a qualified
class name (eg. module.name.classname)
prefix -- method prefix.
'''
if inspect.isclass(base):
self.base_class_name = base.__name__
self.base_module_name = inspect.getmodule(base).__name__
else:
self.base_module_name, self.base_class_name = base.rsplit('.', 1)
self.wsdl = None
self.method_prefix = prefix
self._service_class = SOAPService
self.header = None
self.imports = None
self.messages = []
self._services = None
self.types_module_path = None
self.types_module_name = None
self.messages_module_name = None