Python types 模块,InstanceType() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用types.InstanceType()。
def latestVersionOf(self, anObject):
"""Get the latest version of an object.
This can handle just about anything callable; instances, functions,
methods, and classes.
"""
t = type(anObject)
if t == types.FunctionType:
return latestFunction(anObject)
elif t == types.MethodType:
if anObject.im_self is None:
return getattr(anObject.im_class, anObject.__name__)
else:
return getattr(anObject.im_self, anObject.__name__)
elif t == types.InstanceType:
# Kick it, if it's out of date.
getattr(anObject, 'nothing', None)
return anObject
elif t == types.ClassType:
return latestClass(anObject)
else:
log.msg('warning returning anObject!')
return anObject
def __init__(self, method, identifier):
function = method.im_func
if type(function) is types.InstanceType:
function = function.__call__.im_func
ExplorerFunction.__init__(self, function, identifier)
self.id = id(method)
self.klass = explorerPool.getExplorer(method.im_class,
identifier + '.im_class')
self.self = explorerPool.getExplorer(method.im_self,
identifier + '.im_self')
if method.im_self:
# I'm a bound method -- eat the 'self' arg.
self.signature.discardSelf()
def collect_variables(self, vars, objects, names, treated, skip_unknown = False):
for name in names:
if name not in treated:
try:
obj = objects[name]
try:
if sys.version[0] == '2' and type(obj) is types.InstanceType:
type_name = "instance (" + obj.__class__.__name__ + ")"
else:
type_name = type(obj).__name__
except:
type_name = 'unknown'
except:
if skip_unknown:
continue
obj = SynthesizedValue('<undefined>', len_value=0)
type_name = 'unknown'
vars.append((name, type(obj), safe_repr(obj), safe_hex_repr(obj), type_name, get_object_len(obj)))
treated.add(name)
def collect_variables(self, vars, objects, names, treated, skip_unknown = False):
for name in names:
if name not in treated:
try:
obj = objects[name]
try:
if sys.version[0] == '2' and type(obj) is types.InstanceType:
type_name = "instance (" + obj.__class__.__name__ + ")"
else:
type_name = type(obj).__name__
except:
type_name = 'unknown'
except:
if skip_unknown:
continue
obj = SynthesizedValue('<undefined>', len_value=0)
type_name = 'unknown'
vars.append((name, type(obj), safe_repr(obj), safe_hex_repr(obj), type_name, get_object_len(obj)))
treated.add(name)
def _invokePYRO(self, *vargs, **kargs):
result = unwrap(apply(Pyro.core.DynamicProxyWithAttrs._invokePYRO,
tuple([self] + wrap(list(vargs))), wrap(kargs)))
if type(result) is types.InstanceType and \
isinstance(result, Error) or \
isinstance(result, Pyro.errors.PyroError) or \
isinstance(result, ProtocolError):
msg = str(result)
type_name = msg[: msg.find(' ')]
if type_name == 'exceptions.IndexError':
try:
real_type = eval(type_name)
msg = msg.split('\n')[0]
result = real_type(msg[msg.find(':') + 2 :])
except:
pass
raise result
else:
return result
def unwrap(value):
t = type(value)
if t is types.InstanceType and isinstance(value, DynamicProxy):
if pyro_daemon:
try:
return pyro_daemon.getLocalObject(value.objectID)
except KeyError:
pass
return value
elif t is types.ListType:
for i in range(len(value)):
value[i] = unwrap(value[i])
elif t is types.TupleType:
value = list(value)
for i in range(len(value)):
value[i] = unwrap(value[i])
return tuple(value)
elif t is types.DictType:
for k, v in value.items():
value[k] = unwrap(v)
return value
def register(cls, action):
action_logger.info("Registering action :%s" % action)
if isinstance(action, (types.FunctionType, staticmethod)):
name = action.__name__
cls._actions[name.upper()] = action
setattr(cls, name, action)
elif isinstance(action, types.ClassType) and hasattr(action, "__call__"):
name = action.__name__
action = action()
cls._actions[name.upper()] = action
setattr(cls, name, action)
elif (isinstance(action, (types.InstanceType, types.ObjectType))
and hasattr(action, "__call__")):
if isinstance(action, type):
name = action.__name__
action = action()
else:
name = action.__class__.__name__
cls._actions[name.upper()] = action
setattr(cls, name, action)
else:
name = str(action)
action_logger.error("Error registering action :%s" % action)
raise UnknownAction("unable to register action %s!!" %name)
def register(cls, event):
exe_logger.info("Registering event :%s" % event)
if isinstance(event, (types.FunctionType, staticmethod)):
name = event.__name__
cls._chaos_events[name.upper()] = event
setattr(cls, name, event)
elif isinstance(event, types.ClassType) and hasattr(event, "__call__"):
name = event.__name__
event = event()
cls._chaos_events[name.upper()] = event
setattr(cls, name, event)
elif (isinstance(event, (types.InstanceType, types.ObjectType))
and hasattr(event, "__call__")):
if isinstance(event, type):
name = event.__name__
event = event()
else:
name = event.__class__.__name__
cls._chaos_events[name.upper()] = event
setattr(cls, name, event)
else:
name = str(event)
exe_logger.error("Error registering event :%s" % event)
raise UnknownChaosEvent("unable to register event %s!!" % name)
def _invoke_callbacks(self):
for callback in self._done_callbacks:
try:
callback(self)
except Exception:
LOGGER.exception('exception calling callback for %r', self)
except BaseException:
# Explicitly let all other new-style exceptions through so
# that we can catch all old-style exceptions with a simple
# "except:" clause below.
#
# All old-style exception objects are instances of
# types.InstanceType, but "except types.InstanceType:" does
# not catch old-style exceptions for some reason. Thus, the
# only way to catch all old-style exceptions without catching
# any new-style exceptions is to filter out the new-style
# exceptions, which all derive from BaseException.
raise
except:
# Because of the BaseException clause above, this handler only
# executes for old-style exception objects.
LOGGER.exception('exception calling callback for %r', self)
def error(self, obj, value):
kind = type(value)
if six.PY2 and kind is InstanceType:
msg = 'class %s' % value.__class__.__name__
else:
msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
if obj is not None:
e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
% (self.name, class_of(obj),
self.info(), msg)
else:
e = "The '%s' trait must be %s, but a value of %r was specified." \
% (self.name, self.info(), msg)
raise TraitError(e)
def latestVersionOf(self, anObject):
"""Get the latest version of an object.
This can handle just about anything callable; instances, functions,
methods, and classes.
"""
t = type(anObject)
if t == types.FunctionType:
return latestFunction(anObject)
elif t == types.MethodType:
if anObject.im_self is None:
return getattr(anObject.im_class, anObject.__name__)
else:
return getattr(anObject.im_self, anObject.__name__)
elif t == types.InstanceType:
# Kick it, if it's out of date.
getattr(anObject, 'nothing', None)
return anObject
elif t == types.ClassType:
return latestClass(anObject)
else:
log.msg('warning returning anObject!')
return anObject
def __init__(self, method, identifier):
function = method.im_func
if type(function) is types.InstanceType:
function = function.__call__.im_func
ExplorerFunction.__init__(self, function, identifier)
self.id = id(method)
self.klass = explorerPool.getExplorer(method.im_class,
identifier + '.im_class')
self.self = explorerPool.getExplorer(method.im_self,
identifier + '.im_self')
if method.im_self:
# I'm a bound method -- eat the 'self' arg.
self.signature.discardSelf()
def save(self, width='100%', height='100%'):
""" Write the XML string to **filename**. """
test = False
import io
# Fix height and width
self['height'] = height
self['width'] = width
if sys.version_info[0] == 2:
test = type(self.filename) == types.FileType or type(self.filename) == types.InstanceType
elif sys.version_info[0] == 3:
test = type(self.filename) == io.TextIOWrapper
if test:
self.write(self.filename)
else:
fileobj = io.open(str(self.filename), mode='w', encoding='utf-8')
self.write(fileobj)
fileobj.close()
############################################################################
def error(self, obj, value):
kind = type(value)
if six.PY2 and kind is InstanceType:
msg = 'class %s' % value.__class__.__name__
else:
msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
if obj is not None:
e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
% (self.name, class_of(obj),
self.info(), msg)
else:
e = "The '%s' trait must be %s, but a value of %r was specified." \
% (self.name, self.info(), msg)
raise TraitError(e)
def pdef(self, obj, oname=''):
"""Print the call signature for any callable object.
If the object is a class, print the constructor information."""
if not callable(obj):
print('Object is not callable.')
return
header = ''
if inspect.isclass(obj):
header = self.__head('Class constructor information:\n')
elif (not py3compat.PY3) and type(obj) is types.InstanceType:
obj = obj.__call__
output = self._getdef(obj,oname)
if output is None:
self.noinfo('definition header',oname)
else:
print(header,self.format(output), end=' ')
# In Python 3, all classes are new-style, so they all have __init__.
def collect_variables(self, vars, objects, names, treated, skip_unknown = False):
for name in names:
if name not in treated:
try:
obj = objects[name]
try:
if sys.version[0] == '2' and type(obj) is types.InstanceType:
type_name = "instance (" + obj.__class__.__name__ + ")"
else:
type_name = type(obj).__name__
except:
type_name = 'unknown'
except:
if skip_unknown:
continue
obj = SynthesizedValue('<undefined>', len_value=0)
type_name = 'unknown'
vars.append((name, type(obj), safe_repr(obj), safe_hex_repr(obj), type_name, get_object_len(obj)))
treated.add(name)
def _invoke_callbacks(self):
for callback in self._done_callbacks:
try:
callback(self)
except Exception:
LOGGER.exception('exception calling callback for %r', self)
except BaseException:
# Explicitly let all other new-style exceptions through so
# that we can catch all old-style exceptions with a simple
# "except:" clause below.
#
# All old-style exception objects are instances of
# types.InstanceType, but "except types.InstanceType:" does
# not catch old-style exceptions for some reason. Thus, the
# only way to catch all old-style exceptions without catching
# any new-style exceptions is to filter out the new-style
# exceptions, which all derive from BaseException.
raise
except:
# Because of the BaseException clause above, this handler only
# executes for old-style exception objects.
LOGGER.exception('exception calling callback for %r', self)
def getrefs(i, depth):
"""Get the i'th object in memory, return objects that reference it"""
import sys, gc, types
o = sys.getobjects(i)[-1]
for d in range(depth):
for ref in gc.get_referrers(o):
if type(ref) in (types.ListType, types.DictType,
types.InstanceType):
if type(ref) is types.DictType and ref.has_key('copyright'):
continue
o = ref
break
else:
print "Max depth ", d
return o
return o
def collect_variables(self, vars, objects, names, treated, skip_unknown = False):
for name in names:
if name not in treated:
try:
obj = objects[name]
try:
if sys.version[0] == '2' and type(obj) is types.InstanceType:
type_name = "instance (" + obj.__class__.__name__ + ")"
else:
type_name = type(obj).__name__
except:
type_name = 'unknown'
except:
if skip_unknown:
continue
obj = SynthesizedValue('<undefined>', len_value=0)
type_name = 'unknown'
vars.append((name, type(obj), safe_repr(obj), safe_hex_repr(obj), type_name, get_object_len(obj)))
treated.add(name)
def try_serialize_handler(handler):
"""Try to serialize map/reduce handler.
Args:
handler: handler function/instance. Handler can be a function or an
instance of a callable class. In the latter case, the handler will
be serialized across slices to allow users to save states.
Returns:
serialized handler string or None.
"""
if (isinstance(handler, types.InstanceType) or
(isinstance(handler, object) and
not inspect.isfunction(handler) and
not inspect.ismethod(handler)) and
hasattr(handler, "__call__")):
return pickle.dumps(handler)
return None
def collect_variables(self, vars, objects, names, treated, skip_unknown = False):
for name in names:
if name not in treated:
try:
obj = objects[name]
try:
if sys.version[0] == '2' and type(obj) is types.InstanceType:
type_name = "instance (" + obj.__class__.__name__ + ")"
else:
type_name = type(obj).__name__
except:
type_name = 'unknown'
except:
if skip_unknown:
continue
obj = SynthesizedValue('<undefined>', len_value=0)
type_name = 'unknown'
vars.append((name, type(obj), safe_repr(obj), safe_hex_repr(obj), type_name, get_object_len(obj)))
treated.add(name)
def pdef(self, obj, oname=''):
"""Print the call signature for any callable object.
If the object is a class, print the constructor information.
"""
if not callable(obj):
print('Object is not callable.')
return
header = ''
if inspect.isclass(obj):
header = self.__head('Class constructor information:\n')
obj = obj.__init__
elif (not ISPY3K) and type(obj) is types.InstanceType:
obj = obj.__call__
output = self._getdef(obj, oname)
if output is None:
self.noinfo('definition header', oname)
else:
print(header, output, end=' ', file=sys.stdout)
def formatDevicesList(self, devicesCount):
pack_format = '>'
i = 0
for field in self._fields_:
if (i == devicesCount + 2):
break
if type(field[1]) is types.InstanceType:
if BaseStucture in field[1].__class__.__bases__:
pack_format += str(field[1].size()) + 's'
elif 'si' == field[1]:
pack_format += 'c'
elif '<' in field[1]:
pack_format += field[1][1:]
else:
pack_format += field[1]
i += 1
return pack_format
def packDevicesList(self, devicesCount):
values = []
i = 0
for field in self._fields_:
if (i == devicesCount + 2):
break
if type(field[1]) is types.InstanceType:
if BaseStucture in field[1].__class__.__bases__:
values.append(getattr(self, field[0], 0).pack())
else:
if 'si' == field[1]:
values.append(chr(getattr(self, field[0], 0)))
else:
values.append(getattr(self, field[0], 0))
i += 1
return struct.pack(self.formatDevicesList(devicesCount), *values)
def latestVersionOf(self, anObject):
"""
Get the latest version of an object.
This can handle just about anything callable; instances, functions,
methods, and classes.
"""
t = type(anObject)
if t == types.FunctionType:
return latestFunction(anObject)
elif t == types.MethodType:
if anObject.im_self is None:
return getattr(anObject.im_class, anObject.__name__)
else:
return getattr(anObject.im_self, anObject.__name__)
elif t == types.InstanceType:
# Kick it, if it's out of date.
getattr(anObject, 'nothing', None)
return anObject
elif t == types.ClassType:
return latestClass(anObject)
else:
log.msg('warning returning anObject!')
return anObject
def itype(obj):
# version of type that gives more complete information about instance types
global dtoolSuperBase
t = type(obj)
if t is types.InstanceType:
return '%s of <class %s>>' % (repr(types.InstanceType)[:-1],
str(obj.__class__))
else:
# C++ object instances appear to be types via type()
# check if this is a C++ object
if dtoolSuperBase is None:
_getDtoolSuperBase()
if isinstance(obj, dtoolSuperBase):
return '%s of %s>' % (repr(types.InstanceType)[:-1],
str(obj.__class__))
return t
def unwrap_args(args, kw):
#debug!
# c=0
# for x in args:
# if isinstance(x, Expr):
# print "arg %d, EXPR: %s" % (c, str(x))
# else:
# if type(x) == types.InstanceType:
# print "arg %d, Z3: %s" %(c, x.__class__)
# else:
# print "arg %d, Z3: %s" %(c, type(x))
# print traceback.print_stack()
# c+=1
newargs=[x.__backend__() if isinstance(x, Expr) else x for x in args]
if isinstance(kw, dict):
newkw=dict(starmap(lambda k,v: (k, v if not isinstance(v, Expr) else v.__backend__()), kw.iteritems()))
else:
newkw=kw
return (newargs, newkw)
def updateReferencingListAttrs(self):
"""Update all referencing list attributes.
Checks through all object references, and asks each referenced
object to remove us from any list attributes that they might have.
"""
for attr in self.klass().allAttrs():
if isinstance(attr, ObjRefAttr):
value = getattr(self, '_' + attr.name())
if value is not None:
if isinstance(value, (MiddleObject, InstanceType)):
value.removeObjectFromListAttrs(self)
elif isinstance(value, long):
obj = self.store().objRefInMem(value)
if obj:
obj.removeObjectFromListAttrs(self)
def collect_variables(self, vars, objects, names, treated, skip_unknown = False):
for name in names:
if name not in treated:
try:
obj = objects[name]
try:
if sys.version[0] == '2' and type(obj) is types.InstanceType:
type_name = "instance (" + obj.__class__.__name__ + ")"
else:
type_name = type(obj).__name__
except:
type_name = 'unknown'
except:
if skip_unknown:
continue
obj = SynthesizedValue('<undefined>', len_value=0)
type_name = 'unknown'
vars.append((name, type(obj), safe_repr(obj), safe_hex_repr(obj), type_name, get_object_len(obj)))
treated.add(name)
def error(self, obj, value):
kind = type(value)
if (not py3compat.PY3) and kind is InstanceType:
msg = 'class %s' % value.__class__.__name__
else:
msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
if obj is not None:
e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
% (self.name, class_of(obj),
self.info(), msg)
else:
e = "The '%s' trait must be %s, but a value of %r was specified." \
% (self.name, self.info(), msg)
raise TraitError(e)
def pdef(self, obj, oname=''):
"""Print the call signature for any callable object.
If the object is a class, print the constructor information."""
if not callable(obj):
print('Object is not callable.')
return
header = ''
if inspect.isclass(obj):
header = self.__head('Class constructor information:\n')
elif (not py3compat.PY3) and type(obj) is types.InstanceType:
obj = obj.__call__
output = self._getdef(obj,oname)
if output is None:
self.noinfo('definition header',oname)
else:
print(header,self.format(output), end=' ')
# In Python 3, all classes are new-style, so they all have __init__.
def in_idle():
"""
@rtype: C{boolean}
@return: true if this function is run within idle. Tkinter
programs that are run in idle should never call L{Tk.mainloop}; so
this function should be used to gate all calls to C{Tk.mainloop}.
@warning: This function works by checking C{sys.stdin}. If the
user has modified C{sys.stdin}, then it may return incorrect
results.
"""
import sys, types
return (type(sys.stdin) == types.InstanceType and \
sys.stdin.__class__.__name__ == 'PyShell')
##//////////////////////////////////////////////////////
## Test code.
##//////////////////////////////////////////////////////
def in_idle():
"""
@rtype: C{boolean}
@return: true if this function is run within idle. Tkinter
programs that are run in idle should never call L{Tk.mainloop}; so
this function should be used to gate all calls to C{Tk.mainloop}.
@warning: This function works by checking C{sys.stdin}. If the
user has modified C{sys.stdin}, then it may return incorrect
results.
"""
import sys, types
return (type(sys.stdin) == types.InstanceType and \
sys.stdin.__class__.__name__ == 'PyShell')
##//////////////////////////////////////////////////////
## Test code.
##//////////////////////////////////////////////////////
def collect_variables(self, vars, objects, names, treated, skip_unknown = False):
for name in names:
if name not in treated:
try:
obj = objects[name]
try:
if sys.version[0] == '2' and type(obj) is types.InstanceType:
type_name = "instance (" + obj.__class__.__name__ + ")"
else:
type_name = type(obj).__name__
except:
type_name = 'unknown'
except:
if skip_unknown:
continue
obj = SynthesizedValue('<undefined>', len_value=0)
type_name = 'unknown'
vars.append((name, type(obj), safe_repr(obj), safe_hex_repr(obj), type_name, get_object_len(obj)))
treated.add(name)
def error(self, obj, value):
kind = type(value)
if six.PY2 and kind is InstanceType:
msg = 'class %s' % value.__class__.__name__
else:
msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
if obj is not None:
e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
% (self.name, class_of(obj),
self.info(), msg)
else:
e = "The '%s' trait must be %s, but a value of %r was specified." \
% (self.name, self.info(), msg)
raise TraitError(e)
def in_idle():
"""
@rtype: C{boolean}
@return: true if this function is run within idle. Tkinter
programs that are run in idle should never call L{Tk.mainloop}; so
this function should be used to gate all calls to C{Tk.mainloop}.
@warning: This function works by checking C{sys.stdin}. If the
user has modified C{sys.stdin}, then it may return incorrect
results.
"""
import sys, types
return (type(sys.stdin) == types.InstanceType and \
sys.stdin.__class__.__name__ == 'PyShell')
##//////////////////////////////////////////////////////
## Test code.
##//////////////////////////////////////////////////////
def __init__(self,data):
self.change = 0
self.maxtype = 0
self.data = data
if type(data) is types.InstanceType and ".dump" in str(data.__class__):
self.which = 0
elif type(data) is types.InstanceType and ".data" in str(data.__class__):
self.which = 0
elif type(data) is types.InstanceType and ".mdump" in str(data.__class__):
self.which = 1
elif type(data) is types.InstanceType and ".cdata" in str(data.__class__):
self.which = 1
else:
raise StandardError,"unrecognized object passed to ensight"
# --------------------------------------------------------------------
def dis(x=None):
"""Disassemble classes, methods, functions, or code.
With no argument, disassemble the last traceback.
"""
if x is None:
distb()
return
if isinstance(x, types.InstanceType):
x = x.__class__
if hasattr(x, 'im_func'):
x = x.im_func
if hasattr(x, 'func_code'):
x = x.func_code
if hasattr(x, '__dict__'):
items = x.__dict__.items()
items.sort()
for name, x1 in items:
if isinstance(x1, _have_code):
print "Disassembly of %s:" % name
try:
dis(x1)
except TypeError, msg:
print "Sorry:", msg
print
elif hasattr(x, 'co_code'):
disassemble(x)
elif isinstance(x, str):
disassemble_string(x)
else:
raise TypeError, \
"don't know how to disassemble %s objects" % \
type(x).__name__
def describe(thing):
"""Produce a short description of the given thing."""
if inspect.ismodule(thing):
if thing.__name__ in sys.builtin_module_names:
return 'built-in module ' + thing.__name__
if hasattr(thing, '__path__'):
return 'package ' + thing.__name__
else:
return 'module ' + thing.__name__
if inspect.isbuiltin(thing):
return 'built-in function ' + thing.__name__
if inspect.isgetsetdescriptor(thing):
return 'getset descriptor %s.%s.%s' % (
thing.__objclass__.__module__, thing.__objclass__.__name__,
thing.__name__)
if inspect.ismemberdescriptor(thing):
return 'member descriptor %s.%s.%s' % (
thing.__objclass__.__module__, thing.__objclass__.__name__,
thing.__name__)
if inspect.isclass(thing):
return 'class ' + thing.__name__
if inspect.isfunction(thing):
return 'function ' + thing.__name__
if inspect.ismethod(thing):
return 'method ' + thing.__name__
if type(thing) is types.InstanceType:
return 'instance of ' + thing.__class__.__name__
return type(thing).__name__
def typeStr(obj):
"""Create a more useful type string by making <instance> types report their class."""
typ = type(obj)
if typ == getattr(types, 'InstanceType', None):
return "<instance of %s>" % obj.__class__.__name__
else:
return str(typ)
def typeStr(obj):
"""Create a more useful type string by making <instance> types report their class."""
typ = type(obj)
if typ == getattr(types, 'InstanceType', None):
return "<instance of %s>" % obj.__class__.__name__
else:
return str(typ)
def represent_data(self, data):
if self.ignore_aliases(data):
self.alias_key = None
else:
self.alias_key = id(data)
if self.alias_key is not None:
if self.alias_key in self.represented_objects:
node = self.represented_objects[self.alias_key]
#if node is None:
# raise RepresenterError("recursive objects are not allowed: %r" % data)
return node
#self.represented_objects[alias_key] = None
self.object_keeper.append(data)
data_types = type(data).__mro__
if type(data) is types.InstanceType:
data_types = self.get_classobj_bases(data.__class__)+list(data_types)
if data_types[0] in self.yaml_representers:
node = self.yaml_representers[data_types[0]](self, data)
else:
for data_type in data_types:
if data_type in self.yaml_multi_representers:
node = self.yaml_multi_representers[data_type](self, data)
break
else:
if None in self.yaml_multi_representers:
node = self.yaml_multi_representers[None](self, data)
elif None in self.yaml_representers:
node = self.yaml_representers[None](self, data)
else:
node = ScalarNode(None, unicode(data))
#if alias_key is not None:
# self.represented_objects[alias_key] = node
return node
def represent_data(self, data):
if self.ignore_aliases(data):
self.alias_key = None
else:
self.alias_key = id(data)
if self.alias_key is not None:
if self.alias_key in self.represented_objects:
node = self.represented_objects[self.alias_key]
#if node is None:
# raise RepresenterError("recursive objects are not allowed: %r" % data)
return node
#self.represented_objects[alias_key] = None
self.object_keeper.append(data)
data_types = type(data).__mro__
if type(data) is types.InstanceType:
data_types = self.get_classobj_bases(data.__class__)+list(data_types)
if data_types[0] in self.yaml_representers:
node = self.yaml_representers[data_types[0]](self, data)
else:
for data_type in data_types:
if data_type in self.yaml_multi_representers:
node = self.yaml_multi_representers[data_type](self, data)
break
else:
if None in self.yaml_multi_representers:
node = self.yaml_multi_representers[None](self, data)
elif None in self.yaml_representers:
node = self.yaml_representers[None](self, data)
else:
node = ScalarNode(None, unicode(data))
#if alias_key is not None:
# self.represented_objects[alias_key] = node
return node
def isinst(inst,clazz):
if type(inst) != types.InstanceType or type(clazz)!=types.ClassType:
return isinstance(inst,clazz)
cl = inst.__class__
cl2 = getcurrent(cl)
clazz = getcurrent(clazz)
if issubclass(cl2,clazz):
if cl == cl2:
return WAS
else:
inst.__class__ = cl2
return IS
else:
return ISNT
def isOfType(start, goal):
return ((type(start) is goal) or
(isinstance(start, types.InstanceType) and
start.__class__ is goal))
def fill_property(self, property, value):
"""Set a value for a particular property.
'property' should be one of the keys in my propertyLabels.
"""
row, name = self.propertyLabels.get(property)
if type(value) is not types.InstanceType:
widget = gtk.Label(str(value))
widget.set_alignment(0, 0)
else:
widget = value.newAttributeWidget(self)
widget.set_name("PropertyValue")
self.subtable['properties'].attach(widget, 1, 2, row, row+1)
def view_get_item(self, perspective, key):
if type(key) is types.InstanceType:
key = key.object
item = self.dct[key]
identifier = "%s[%s]" % (self.identifier, repr(key))
# GLOBAL: using global explorerPool
item = explorerPool.getExplorer(item, identifier)
return item
def dis(x=None):
"""Disassemble classes, methods, functions, or code.
With no argument, disassemble the last traceback.
"""
if x is None:
distb()
return
if isinstance(x, types.InstanceType):
x = x.__class__
if hasattr(x, 'im_func'):
x = x.im_func
if hasattr(x, 'func_code'):
x = x.func_code
if hasattr(x, '__dict__'):
items = x.__dict__.items()
items.sort()
for name, x1 in items:
if isinstance(x1, _have_code):
print "Disassembly of %s:" % name
try:
dis(x1)
except TypeError, msg:
print "Sorry:", msg
print
elif hasattr(x, 'co_code'):
disassemble(x)
elif isinstance(x, str):
disassemble_string(x)
else:
raise TypeError, \
"don't know how to disassemble %s objects" % \
type(x).__name__
def checkrec(self, key, value):
# override this in a subclass if the key type is different
if sys.version_info[0] >= 3 :
if isinstance(key, bytes) :
key = key.decode("iso8859-1") # 8 bits
x = key[1]
if key[0] == 'S':
self.assertEqual(type(value), str)
self.assertEqual(value, 10 * x)
elif key[0] == 'I':
self.assertEqual(type(value), int)
self.assertEqual(value, ord(x))
elif key[0] == 'L':
self.assertEqual(type(value), list)
self.assertEqual(value, [x] * 10)
elif key[0] == 'O':
if sys.version_info[0] < 3 :
from types import InstanceType
self.assertEqual(type(value), InstanceType)
else :
self.assertEqual(type(value), DataClass)
self.assertEqual(value.S, 10 * x)
self.assertEqual(value.I, ord(x))
self.assertEqual(value.L, [x] * 10)
else:
self.assertTrue(0, 'Unknown key type, fix the test')
#----------------------------------------------------------------------
def describe(thing):
"""Produce a short description of the given thing."""
if inspect.ismodule(thing):
if thing.__name__ in sys.builtin_module_names:
return 'built-in module ' + thing.__name__
if hasattr(thing, '__path__'):
return 'package ' + thing.__name__
else:
return 'module ' + thing.__name__
if inspect.isbuiltin(thing):
return 'built-in function ' + thing.__name__
if inspect.isgetsetdescriptor(thing):
return 'getset descriptor %s.%s.%s' % (
thing.__objclass__.__module__, thing.__objclass__.__name__,
thing.__name__)
if inspect.ismemberdescriptor(thing):
return 'member descriptor %s.%s.%s' % (
thing.__objclass__.__module__, thing.__objclass__.__name__,
thing.__name__)
if inspect.isclass(thing):
return 'class ' + thing.__name__
if inspect.isfunction(thing):
return 'function ' + thing.__name__
if inspect.ismethod(thing):
return 'method ' + thing.__name__
if type(thing) is types.InstanceType:
return 'instance of ' + thing.__class__.__name__
return type(thing).__name__