def _list_xml_members(cls):
"""Generator listing all members which are XML elements or attributes.
The following members would be considered XML members:
foo = 'abc' - indicates an XML attribute with the qname abc
foo = SomeElement - indicates an XML child element
foo = [AnElement] - indicates a repeating XML child element, each instance
will be stored in a list in this member
foo = ('att1', '{http://example.com/namespace}att2') - indicates an XML
attribute which has different parsing rules in different versions of
the protocol. Version 1 of the XML parsing rules will look for an
attribute with the qname 'att1' but verion 2 of the parsing rules will
look for a namespaced attribute with the local name of 'att2' and an
XML namespace of 'http://example.com/namespace'.
"""
members = []
for pair in inspect.getmembers(cls):
if not pair[0].startswith('_') and pair[0] != 'text':
member_type = pair[1]
if (isinstance(member_type, tuple) or isinstance(member_type, list)
or isinstance(member_type, (str, unicode))
or (inspect.isclass(member_type)
and issubclass(member_type, XmlElement))):
members.append(pair)
return members
python类isclass()的实例源码
def get_defining_item(self, code):
for modname, mod in sys.modules.iteritems():
file = getattr(mod, '__file__', '').replace('.pyc', '.py')
if file == code.co_filename:
for classname,clazz in inspect.getmembers(mod, predicate=inspect.isclass):
for name,member in inspect.getmembers(clazz, predicate=inspect.ismethod):
filename = member.im_func.func_code.co_filename
lineno = member.im_func.func_code.co_firstlineno
if filename == code.co_filename and lineno == code.co_firstlineno:
self.imports_.add((modname, clazz.__name__))
return clazz, member
for name,member in inspect.getmembers(clazz, predicate=inspect.isfunction):
filename = member.func_code.co_filename
lineno = member.func_code.co_firstlineno
if filename == code.co_filename and lineno == code.co_firstlineno:
self.imports_.add((modname, clazz.__name__))
return clazz, member
self.imports_.add((modname,))
return mod, mod
def __init__(self, renderer=None, inline=None, block=None, **kwargs):
if not renderer:
renderer = Renderer(**kwargs)
else:
kwargs.update(renderer.options)
self.renderer = renderer
if inline and inspect.isclass(inline):
inline = inline(renderer, **kwargs)
if block and inspect.isclass(block):
block = block(**kwargs)
if inline:
self.inline = inline
else:
self.inline = InlineLexer(renderer, **kwargs)
self.block = block or BlockLexer(BlockGrammar())
self.footnotes = []
self.tokens = []
# detect if it should parse text in block html
self._parse_block_html = kwargs.get('parse_block_html')
def get_doc_object(obj, what=None, config=None):
if what is None:
if inspect.isclass(obj):
what = 'class'
elif inspect.ismodule(obj):
what = 'module'
elif callable(obj):
what = 'function'
else:
what = 'object'
if what == 'class':
doc = SphinxTraitsDoc(obj, '', func_doc=SphinxFunctionDoc, config=config)
if looks_like_issubclass(obj, 'HasTraits'):
for name, trait, comment in comment_eater.get_class_traits(obj):
# Exclude private traits.
if not name.startswith('_'):
doc['Traits'].append((name, trait, comment.splitlines()))
return doc
elif what in ('function', 'method'):
return SphinxFunctionDoc(obj, '', config=config)
else:
return SphinxDocString(pydoc.getdoc(obj), config=config)
def get_doc_object(obj, what=None, doc=None, config={}):
if what is None:
if inspect.isclass(obj):
what = 'class'
elif inspect.ismodule(obj):
what = 'module'
elif callable(obj):
what = 'function'
else:
what = 'object'
if what == 'class':
return SphinxClassDoc(obj, func_doc=SphinxFunctionDoc, doc=doc,
config=config)
elif what in ('function', 'method'):
return SphinxFunctionDoc(obj, doc=doc, config=config)
else:
if doc is None:
doc = pydoc.getdoc(obj)
return SphinxObjDoc(obj, doc, config=config)
def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc,
config={}):
if not inspect.isclass(cls) and cls is not None:
raise ValueError("Expected a class or None, but got %r" % cls)
self._cls = cls
if modulename and not modulename.endswith('.'):
modulename += '.'
self._mod = modulename
if doc is None:
if cls is None:
raise ValueError("No class or documentation string given")
doc = pydoc.getdoc(cls)
NumpyDocString.__init__(self, doc)
if config.get('show_class_members', True):
if not self['Methods']:
self['Methods'] = [(name, '', '')
for name in sorted(self.methods)]
if not self['Attributes']:
self['Attributes'] = [(name, '', '')
for name in sorted(self.properties)]
def name_for(obj):
"""
Get a name for something.
Allows overriding of default names using the `__alias__` attribute.
"""
if isinstance(obj, string_types):
return obj
cls = obj if isclass(obj) else obj.__class__
if hasattr(cls, "__alias__"):
return underscore(cls.__alias__)
else:
return underscore(cls.__name__)
def check_and_create_device(self, info, addr) -> Optional[Device]:
"""Create a corresponding :class:`Device` implementation
for a given info and address.."""
name = info.name
for identifier, v in DEVICE_MAP.items():
if name.startswith(identifier):
if inspect.isclass(v):
_LOGGER.debug("Found a supported '%s', using '%s' class",
name, v.__name__)
return create_device(addr, v)
elif callable(v):
dev = Device(ip=addr)
_LOGGER.info("%s: token: %s",
v(info),
pretty_token(dev.do_discover().checksum))
return None
_LOGGER.warning("Found unsupported device %s at %s, "
"please report to developers", name, addr)
return None
def _construct(self):
logger.debug("Initializing stack")
for s in self.__stack:
if type(s) is tuple:
logger.warn("Implicit declaration of parallel layers in a tuple is deprecated, pass a YowParallelLayer instead")
inst = YowParallelLayer(s)
else:
if inspect.isclass(s):
if issubclass(s, YowLayer):
inst = s()
else:
raise ValueError("Stack must contain only subclasses of YowLayer")
elif issubclass(s.__class__, YowLayer):
inst = s
else:
raise ValueError("Stack must contain only subclasses of YowLayer")
#inst = s()
logger.debug("Constructed %s" % inst)
inst.setStack(self)
self.__stackInstances.append(inst)
for i in range(0, len(self.__stackInstances)):
upperLayer = self.__stackInstances[i + 1] if (i + 1) < len(self.__stackInstances) else None
lowerLayer = self.__stackInstances[i - 1] if i > 0 else None
self.__stackInstances[i].setLayers(upperLayer, lowerLayer)
def get_doc_object(obj, what=None, doc=None, config={}):
if what is None:
if inspect.isclass(obj):
what = 'class'
elif inspect.ismodule(obj):
what = 'module'
elif callable(obj):
what = 'function'
else:
what = 'object'
if what == 'class':
return SphinxClassDoc(obj, func_doc=SphinxFunctionDoc, doc=doc,
config=config)
elif what in ('function', 'method'):
return SphinxFunctionDoc(obj, doc=doc, config=config)
else:
if doc is None:
doc = pydoc.getdoc(obj)
return SphinxObjDoc(obj, doc, config=config)
def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc,
config=None):
if not inspect.isclass(cls) and cls is not None:
raise ValueError("Expected a class or None, but got %r" % cls)
self._cls = cls
if modulename and not modulename.endswith('.'):
modulename += '.'
self._mod = modulename
if doc is None:
if cls is None:
raise ValueError("No class or documentation string given")
doc = pydoc.getdoc(cls)
NumpyDocString.__init__(self, doc)
if config is not None and config.get('show_class_members', True):
if not self['Methods']:
self['Methods'] = [(name, '', '')
for name in sorted(self.methods)]
if not self['Attributes']:
self['Attributes'] = [(name, '', '')
for name in sorted(self.properties)]
def mangle_signature(app, what, name, obj,
options, sig, retann):
# Do not try to inspect classes that don't define `__init__`
if (inspect.isclass(obj) and
(not hasattr(obj, '__init__') or
'initializes x; see ' in pydoc.getdoc(obj.__init__))):
return '', ''
if not (callable(obj) or hasattr(obj, '__argspec_is_invalid_')):
return
if not hasattr(obj, '__doc__'):
return
doc = SphinxDocString(pydoc.getdoc(obj))
if doc['Signature']:
sig = re.sub("^[^(]*", "", doc['Signature'])
return sig, ''
def _toStardardCondition(condition):
'''?????????????????'''
if inspect.isclass(condition):
return lambda x: isinstance(x, condition)
if isinstance(condition, (tuple, list)):
cls, condition = condition[:2]
if condition is None:
return _toStardardCondition(cls)
if cls in (str, unicode) and condition[0] == condition[-1] == '/':
return lambda x: (isinstance(x, cls)
and re.match(condition[1:-1], x) is not None)
return lambda x: isinstance(x, cls) and eval(condition)
return condition
def _toStardardCondition(condition):
'''?????????????????'''
# class condition
if inspect.isclass(condition):
info = "must be %s type" % condition.__name__
return lambda x: isinstance(x, condition) or info
if isinstance(condition, (tuple, list)):
cls, condition = condition[:2]
if condition is None:
return _toStardardCondition(cls)
# regular condition
if cls in (str, unicode) and condition[0] == condition[-1] == '/':
info = 'must match regular expression: %s' % condition
return lambda x: (isinstance(x, cls) and re.match(condition[1:-1], x) is not None) or info
# pure str condition
info = 'must satisfy rule: %s' % condition
return lambda x: (isinstance(x, cls) and eval(condition)) or info
# fcuntion condition
return condition
def nice_classname(obj):
"""Returns a nice name for class object or class instance.
>>> nice_classname(Exception()) # doctest: +ELLIPSIS
'...Exception'
>>> nice_classname(Exception) # doctest: +ELLIPSIS
'...Exception'
"""
if inspect.isclass(obj):
cls_name = obj.__name__
else:
cls_name = obj.__class__.__name__
mod = inspect.getmodule(obj)
if mod:
name = mod.__name__
# jython
if name.startswith('org.python.core.'):
name = name[len('org.python.core.'):]
return "%s.%s" % (name, cls_name)
else:
return cls_name
def check_handler(value):
h = None
HANDLER_PREFIX = "handler_"
name = HANDLER_PREFIX + "base"
base_mod = load_mod(PKG_NAME, name)
if not base_mod:
print("load module %s failed" % (name), file=sys.stderr)
sys.exit(1)
try:
base_cls = getattr(base_mod, "HandlerBase")
except AttributeError as e:
print("err=%s, can't find HandlerBase class" % (e), file=sys.stderr)
sys.exit(1)
name = HANDLER_PREFIX + value
mod = load_mod(PKG_NAME, name)
if not mod:
print("load module %s failed" % (name), file=sys.stderr)
sys.exit(1)
for v in dir(mod):
cls = getattr(mod, v)
if inspect.isclass(cls) and issubclass(cls, base_cls):
return cls()
if h is None:
raise argparse.ArgumentTypeError("%s is an invalid handler" % value)
def modulemap():
"""Returns a dictionary where `type_name`s are mapped
to corresponding classes from `gamelocker.datatypes`.
:return: A dictionary with keys of `type_name`
and values of :class:`DataMessage` subclasses.
:rtype: :class:`gamelocker.janus.DataMessage`
"""
typemap = dict()
classes = inspect.getmembers(sys.modules[__name__], inspect.isclass)
for name, value in classes:
if name == "Attribute" or name == "DataMessage":
continue
typemap[value.type_name] = value
return typemap
def type_name(value):
"""
Returns a user-readable name for the type of an object
:param value:
A value to get the type name of
:return:
A unicode string of the object's type name
"""
if inspect.isclass(value):
cls = value
else:
cls = value.__class__
if cls.__module__ in set(['builtins', '__builtin__']):
return cls.__name__
return '%s.%s' % (cls.__module__, cls.__name__)
def get_spider_class(spider_name, spiders_directory=None):
spider_class = None
spider_module_name = get_spider_module_name(spider_name)
if spider_module_name in get_spiders_modules_names(spiders_directory):
spider_module = import_module(spider_module_name)
for module_attribute_name in dir(spider_module):
module_attribute = getattr(spider_module, module_attribute_name)
if inspect.isclass(module_attribute) \
and module_attribute is not JobSpider \
and issubclass(module_attribute, JobSpider):
spider_class = module_attribute
break
return spider_class
def load():
"""Load the active experiment."""
if os.getcwd() not in sys.path:
sys.path.append(os.getcwd())
try:
exp = imp.load_source('dallinger_experiment', "dallinger_experiment.py")
classes = inspect.getmembers(exp, inspect.isclass)
exps = [c for c in classes
if (c[1].__bases__[0].__name__ in "Experiment")]
this_experiment = exps[0][0]
mod = __import__('dallinger_experiment', fromlist=[this_experiment])
return getattr(mod, this_experiment)
except ImportError:
logger.error('Could not import experiment.')
raise