def fileopen(self, file):
import types
if repr(type(file)) != "<type 'file'>":
raise TypeError, 'posixfile.fileopen() arg must be file object'
self._file_ = file
# Copy basic file methods
for maybemethod in dir(file):
if not maybemethod.startswith('_'):
attr = getattr(file, maybemethod)
if isinstance(attr, types.BuiltinMethodType):
setattr(self, maybemethod, attr)
return self
#
# New methods
#
python类BuiltinMethodType()的实例源码
def fileopen(self, file):
import types
if repr(type(file)) != "<type 'file'>":
raise TypeError, 'posixfile.fileopen() arg must be file object'
self._file_ = file
# Copy basic file methods
for maybemethod in dir(file):
if not maybemethod.startswith('_'):
attr = getattr(file, maybemethod)
if isinstance(attr, types.BuiltinMethodType):
setattr(self, maybemethod, attr)
return self
#
# New methods
#
def obj2dict(obj, processed=None):
"""
converts any object into a dict, recursively
"""
processed = processed if not processed is None else set()
if obj is None:
return None
if isinstance(obj,(int,long,str,unicode,float,bool)):
return obj
if id(obj) in processed:
return '<reference>'
processed.add(id(obj))
if isinstance(obj,(list,tuple)):
return [obj2dict(item,processed) for item in obj]
if not isinstance(obj, dict) and hasattr(obj,'__dict__'):
obj = obj.__dict__
else:
return repr(obj)
return dict((key,obj2dict(value,processed)) for key,value in obj.items()
if not key.startswith('_') and
not type(value) in (types.FunctionType,
types.LambdaType,
types.BuiltinFunctionType,
types.BuiltinMethodType))
def _compute_fields_for_operation(self, fields, to_compute):
row = OpRow(self)
for name, tup in iteritems(fields):
field, value = tup
if isinstance(
value, (
types.LambdaType, types.FunctionType, types.MethodType,
types.BuiltinFunctionType, types.BuiltinMethodType
)
):
value = value()
row.set_value(name, value, field)
for name, field in to_compute:
try:
row.set_value(name, field.compute(row), field)
except (KeyError, AttributeError):
# error silently unless field is required!
if field.required and name not in fields:
raise RuntimeError(
'unable to compute required field: %s' % name)
return row
def obj2dict(obj, processed=None):
"""
converts any object into a dict, recursively
"""
processed = processed if not processed is None else set()
if obj is None:
return None
if isinstance(obj,(int,long,str,unicode,float,bool)):
return obj
if id(obj) in processed:
return '<reference>'
processed.add(id(obj))
if isinstance(obj,(list,tuple)):
return [obj2dict(item,processed) for item in obj]
if not isinstance(obj, dict) and hasattr(obj,'__dict__'):
obj = obj.__dict__
else:
return repr(obj)
return dict((key,obj2dict(value,processed)) for key,value in obj.items()
if not key.startswith('_') and
not type(value) in (types.FunctionType,
types.LambdaType,
types.BuiltinFunctionType,
types.BuiltinMethodType))
def obj2dict(obj, processed=None):
"""
converts any object into a dict, recursively
"""
processed = processed if not processed is None else set()
if obj is None:
return None
if isinstance(obj,(int,long,str,unicode,float,bool)):
return obj
if id(obj) in processed:
return '<reference>'
processed.add(id(obj))
if isinstance(obj,(list,tuple)):
return [obj2dict(item,processed) for item in obj]
if not isinstance(obj, dict) and hasattr(obj,'__dict__'):
obj = obj.__dict__
else:
return repr(obj)
return dict((key,obj2dict(value,processed)) for key,value in obj.items()
if not key.startswith('_') and
not type(value) in (types.FunctionType,
types.LambdaType,
types.BuiltinFunctionType,
types.BuiltinMethodType))
def obj2dict(obj, processed=None):
"""
converts any object into a dict, recursively
"""
processed = processed if not processed is None else set()
if obj is None:
return None
if isinstance(obj,(int,long,str,unicode,float,bool)):
return obj
if id(obj) in processed:
return '<reference>'
processed.add(id(obj))
if isinstance(obj,(list,tuple)):
return [obj2dict(item,processed) for item in obj]
if not isinstance(obj, dict) and hasattr(obj,'__dict__'):
obj = obj.__dict__
else:
return repr(obj)
return dict((key,obj2dict(value,processed)) for key,value in obj.items()
if not key.startswith('_') and
not type(value) in (types.FunctionType,
types.LambdaType,
types.BuiltinFunctionType,
types.BuiltinMethodType))
def fileopen(self, file):
import types
if repr(type(file)) != "<type 'file'>":
raise TypeError, 'posixfile.fileopen() arg must be file object'
self._file_ = file
# Copy basic file methods
for maybemethod in dir(file):
if not maybemethod.startswith('_'):
attr = getattr(file, maybemethod)
if isinstance(attr, types.BuiltinMethodType):
setattr(self, maybemethod, attr)
return self
#
# New methods
#
def fileopen(self, file):
import types
if repr(type(file)) != "<type 'file'>":
raise TypeError, 'posixfile.fileopen() arg must be file object'
self._file_ = file
# Copy basic file methods
for maybemethod in dir(file):
if not maybemethod.startswith('_'):
attr = getattr(file, maybemethod)
if isinstance(attr, types.BuiltinMethodType):
setattr(self, maybemethod, attr)
return self
#
# New methods
#
def handleHello(self, csock, oname, obj, data):
"""
Hello messages are used to get the initial cache of
method names for the newly connected object.
"""
if verbose: print("GOT A HELLO")
self.daemon.increfObject(oname)
ret = {}
for name in dir(obj):
attr = getattr(obj, name, None)
if isinstance(attr, (types.MethodType, types.BuiltinMethodType, types.FunctionType, CobraMethod)):
ret[name] = True
try:
csock.sendMessage(COBRA_HELLO, version, ret)
except CobraClosedException:
pass
def fileopen(self, file):
import types
if repr(type(file)) != "<type 'file'>":
raise TypeError, 'posixfile.fileopen() arg must be file object'
self._file_ = file
# Copy basic file methods
for maybemethod in dir(file):
if not maybemethod.startswith('_'):
attr = getattr(file, maybemethod)
if isinstance(attr, types.BuiltinMethodType):
setattr(self, maybemethod, attr)
return self
#
# New methods
#
def obj2dict(obj, processed=None):
"""
converts any object into a dict, recursively
"""
processed = processed if not processed is None else set()
if obj is None:
return None
if isinstance(obj,(int,long,str,unicode,float,bool)):
return obj
if id(obj) in processed:
return '<reference>'
processed.add(id(obj))
if isinstance(obj,(list,tuple)):
return [obj2dict(item,processed) for item in obj]
if not isinstance(obj, dict) and hasattr(obj,'__dict__'):
obj = obj.__dict__
else:
return repr(obj)
return dict((key,obj2dict(value,processed)) for key,value in obj.items()
if not key.startswith('_') and
not type(value) in (types.FunctionType,
types.LambdaType,
types.BuiltinFunctionType,
types.BuiltinMethodType))
def _compute_fields_for_operation(self, fields, to_compute):
row = OpRow(self)
for name, tup in iteritems(fields):
field, value = tup
if isinstance(
value, (
types.LambdaType, types.FunctionType, types.MethodType,
types.BuiltinFunctionType, types.BuiltinMethodType
)
):
value = value()
row.set_value(name, value, field)
for name, field in to_compute:
try:
row.set_value(name, field.compute(row), field)
except (KeyError, AttributeError):
# error silently unless field is required!
if field.required and name not in fields:
raise RuntimeError(
'unable to compute required field: %s' % name)
return row
def fileopen(self, file):
import types
if repr(type(file)) != "<type 'file'>":
raise TypeError, 'posixfile.fileopen() arg must be file object'
self._file_ = file
# Copy basic file methods
for maybemethod in dir(file):
if not maybemethod.startswith('_'):
attr = getattr(file, maybemethod)
if isinstance(attr, types.BuiltinMethodType):
setattr(self, maybemethod, attr)
return self
#
# New methods
#
def _get_func_repr(func):
if isinstance(func, types.MethodType):
return "{cls}.{func}".format(
cls=func.im_self.__class__,
func=func.im_func.__name__
)
elif isinstance(func, types.BuiltinMethodType):
if not func.__self__:
return "{func}".format(
func=func.__name__
)
else:
return "{type}.{func}".format(
type=func.__self__,
func=func.__name__
)
elif (isinstance(func, types.ObjectType) and hasattr(func, "__call__")) or\
isinstance(func, (types.FunctionType, types.BuiltinFunctionType,
types.ClassType, types.UnboundMethodType)):
return "{module}.{func}".format(
module=func.__module__,
func=func.__name__
)
else:
raise ValueError("func must be callable")
def _get_func_repr(func):
if isinstance(func, types.MethodType):
return "{cls}.{func}".format(
cls=func.im_self.__class__,
func=func.im_func.__name__
)
elif isinstance(func, types.BuiltinMethodType):
if not func.__self__:
return "{func}".format(
func=func.__name__
)
else:
return "{type}.{func}".format(
type=func.__self__,
func=func.__name__
)
elif (isinstance(func, types.ObjectType) and hasattr(func, "__call__")) or\
isinstance(func, (types.FunctionType, types.BuiltinFunctionType,
types.ClassType, types.UnboundMethodType)):
return "{module}.{func}".format(
module=func.__module__,
func=func.__name__
)
else:
raise ValueError("func must be callable")
def obj2dict(obj, processed=None):
"""
converts any object into a dict, recursively
"""
processed = processed if not processed is None else set()
if obj is None:
return None
if isinstance(obj,(int,long,str,unicode,float,bool)):
return obj
if id(obj) in processed:
return '<reference>'
processed.add(id(obj))
if isinstance(obj,(list,tuple)):
return [obj2dict(item,processed) for item in obj]
if not isinstance(obj, dict) and hasattr(obj,'__dict__'):
obj = obj.__dict__
else:
return repr(obj)
return dict((key,obj2dict(value,processed)) for key,value in obj.items()
if not key.startswith('_') and
not type(value) in (types.FunctionType,
types.LambdaType,
types.BuiltinFunctionType,
types.BuiltinMethodType))
def fileopen(self, file):
import types
if repr(type(file)) != "<type 'file'>":
raise TypeError, 'posixfile.fileopen() arg must be file object'
self._file_ = file
# Copy basic file methods
for maybemethod in dir(file):
if not maybemethod.startswith('_'):
attr = getattr(file, maybemethod)
if isinstance(attr, types.BuiltinMethodType):
setattr(self, maybemethod, attr)
return self
#
# New methods
#
def fileopen(self, file):
import types
if repr(type(file)) != "<type 'file'>":
raise TypeError, 'posixfile.fileopen() arg must be file object'
self._file_ = file
# Copy basic file methods
for maybemethod in dir(file):
if not maybemethod.startswith('_'):
attr = getattr(file, maybemethod)
if isinstance(attr, types.BuiltinMethodType):
setattr(self, maybemethod, attr)
return self
#
# New methods
#
def obj2dict(obj, processed=None):
"""
converts any object into a dict, recursively
"""
processed = processed if not processed is None else set()
if obj is None:
return None
if isinstance(obj,(int,long,str,unicode,float,bool)):
return obj
if id(obj) in processed:
return '<reference>'
processed.add(id(obj))
if isinstance(obj,(list,tuple)):
return [obj2dict(item,processed) for item in obj]
if not isinstance(obj, dict) and hasattr(obj,'__dict__'):
obj = obj.__dict__
else:
return repr(obj)
return dict((key,obj2dict(value,processed)) for key,value in obj.items()
if not key.startswith('_') and
not type(value) in (types.FunctionType,
types.LambdaType,
types.BuiltinFunctionType,
types.BuiltinMethodType))
def _randbelow(self, n, int=int, maxsize=1<<BPF, type=type,
Method=_MethodType, BuiltinMethod=_BuiltinMethodType):
"Return a random int in the range [0,n). Raises ValueError if n==0."
random = self.random
getrandbits = self.getrandbits
# Only call self.getrandbits if the original random() builtin method
# has not been overridden or if a new getrandbits() was supplied.
if type(random) is BuiltinMethod or type(getrandbits) is Method:
k = n.bit_length() # don't use (n-1) here because n can be 1
r = getrandbits(k) # 0 <= r < 2**k
while r >= n:
r = getrandbits(k)
return r
# There's an overridden random() method but no new getrandbits() method,
# so we can only use random() from here.
if n >= maxsize:
_warn("Underlying random() generator does not supply \n"
"enough bits to choose from a population range this large.\n"
"To remove the range limitation, add a getrandbits() method.")
return int(random() * n)
rem = maxsize % n
limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0
r = random()
while r >= limit:
r = random()
return int(r*maxsize) % n
## -------------------- sequence methods -------------------
def _randbelow(self, n, _log=_log, int=int, _maxwidth=1L<<BPF,
_Method=_MethodType, _BuiltinMethod=_BuiltinMethodType):
"""Return a random int in the range [0,n)
Handles the case where n has more bits than returned
by a single call to the underlying generator.
"""
try:
getrandbits = self.getrandbits
except AttributeError:
pass
else:
# Only call self.getrandbits if the original random() builtin method
# has not been overridden or if a new getrandbits() was supplied.
# This assures that the two methods correspond.
if type(self.random) is _BuiltinMethod or type(getrandbits) is _Method:
k = int(1.00001 + _log(n-1, 2.0)) # 2**k > n-1 > 2**(k-2)
r = getrandbits(k)
while r >= n:
r = getrandbits(k)
return r
if n >= _maxwidth:
_warn("Underlying random() generator does not supply \n"
"enough bits to choose from a population range this large")
return int(self.random() * n)
## -------------------- sequence methods -------------------
def __getattr__( self, attrName ):
# Look for a cached reference to the attribute and if it isn't there,
# fetch it from the wrapped object.
notThere = 'Not there'
returnAttr = self._cache.get( attrName, notThere )
if returnAttr is notThere:
attr = getattr( self._wrappedObject, attrName, notThere )
if attr is notThere:
# The attribute is missing - let it raise an AttributeError.
getattr( self._wrappedObject, attrName )
# We only wrap C functions, which have the type BuiltinMethodType.
elif isinstance( attr, types.BuiltinMethodType ):
# Base the fictitious filename on the module name or class name.
if isinstance( self._wrappedObject, types.ModuleType ):
objectName = self._wrappedObject.__name__
else:
objectName = type( self._wrappedObject ).__name__
returnAttr = _ProfileWrapFunction( attr, objectName )
self._cache[ attrName ] = returnAttr
# All non-C-function attributes get returned directly.
else:
returnAttr = attr
return returnAttr
def _randbelow(self, n, _log=_log, _int=int, _maxwidth=1L<<BPF,
_Method=_MethodType, _BuiltinMethod=_BuiltinMethodType):
"""Return a random int in the range [0,n)
Handles the case where n has more bits than returned
by a single call to the underlying generator.
"""
try:
getrandbits = self.getrandbits
except AttributeError:
pass
else:
# Only call self.getrandbits if the original random() builtin method
# has not been overridden or if a new getrandbits() was supplied.
# This assures that the two methods correspond.
if type(self.random) is _BuiltinMethod or type(getrandbits) is _Method:
k = _int(1.00001 + _log(n-1, 2.0)) # 2**k > n-1 > 2**(k-2)
r = getrandbits(k)
while r >= n:
r = getrandbits(k)
return r
if n >= _maxwidth:
_warn("Underlying random() generator does not supply \n"
"enough bits to choose from a population range this large")
return _int(self.random() * n)
## -------------------- sequence methods -------------------
def inspect_format_method(callable):
if not isinstance(callable, (types.MethodType,
types.BuiltinMethodType)) or \
callable.__name__ != 'format':
return None
obj = callable.__self__
if isinstance(obj, string_types):
return obj
def inspect_format_method(callable):
if not isinstance(callable, (types.MethodType,
types.BuiltinMethodType)) or \
callable.__name__ != 'format':
return None
obj = callable.__self__
if isinstance(obj, string_types):
return obj
def py_wrap(py):
if isinstance(py, (FunctionType, BuiltinFunctionType, MethodType, BuiltinMethodType,
dict, int, str, bool, float, list, tuple, long, basestring)) or py is None :
return HJs(py)
return PyObjectWrapper(py)
##############################################################################
#Define types
#Object
def _curate_handler(self, handler):
if isinstance(handler, str):
handler = getattr(self, handler)
function_type = (types.FunctionType, types.BuiltinFunctionType)
if isinstance(handler, function_type):
return handler
method_type = (types.MethodType, types.BuiltinMethodType)
if isinstance(handler, method_type):
return unbound_method(handler)
raise TypeError('Unknown handler type "%s"' % type(handler))
def _randbelow(self, n, int=int, maxsize=1<<BPF, type=type,
Method=_MethodType, BuiltinMethod=_BuiltinMethodType):
"Return a random int in the range [0,n). Raises ValueError if n==0."
random = self.random
getrandbits = self.getrandbits
# Only call self.getrandbits if the original random() builtin method
# has not been overridden or if a new getrandbits() was supplied.
if type(random) is BuiltinMethod or type(getrandbits) is Method:
k = n.bit_length() # don't use (n-1) here because n can be 1
r = getrandbits(k) # 0 <= r < 2**k
while r >= n:
r = getrandbits(k)
return r
# There's an overridden random() method but no new getrandbits() method,
# so we can only use random() from here.
if n >= maxsize:
_warn("Underlying random() generator does not supply \n"
"enough bits to choose from a population range this large.\n"
"To remove the range limitation, add a getrandbits() method.")
return int(random() * n)
rem = maxsize % n
limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0
r = random()
while r >= limit:
r = random()
return int(r*maxsize) % n
## -------------------- sequence methods -------------------
def get_py_c_functions(self):
import types
functions = []
for identifier, attr in self._get_py_visible_attrs():
# methods may be python wrappers to C functions
attr_func = getattr(attr, "__func__", attr)
if type(attr_func) in {types.BuiltinMethodType, types.BuiltinFunctionType}:
functions.append((identifier, attr))
return functions