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