def stringify_attributes(attrs):
lines = []
for k, v in attrs.items():
if isinstance(v, (type, types.ClassType)):
lines.append(stringify_class(k, v))
elif isinstance(v, (types.MethodType, type(list.append), type(object.__init__))):
lines.append(stringify_method(k, v))
elif isinstance(v, classmethod):
lines.append(stringify_classmethod(k, v))
elif isinstance(v, (types.FunctionType, types.BuiltinFunctionType, staticmethod)):
lines.append(stringify_function(k, v))
else:
lines.append(stringify_constant(k, v))
return u"\n".join(lines)
python类BuiltinFunctionType()的实例源码
def typeof(self, cdecl):
"""Parse the C type given as a string and return the
corresponding <ctype> object.
It can also be used on 'cdata' instance to get its C type.
"""
if isinstance(cdecl, basestring):
return self._typeof(cdecl)
if isinstance(cdecl, self.CData):
return self._backend.typeof(cdecl)
if isinstance(cdecl, types.BuiltinFunctionType):
res = _builtin_function_type(cdecl)
if res is not None:
return res
if (isinstance(cdecl, types.FunctionType)
and hasattr(cdecl, '_cffi_base_type')):
with self._lock:
return self._get_cached_btype(cdecl._cffi_base_type)
raise TypeError(type(cdecl))
def typeof(self, cdecl):
"""Parse the C type given as a string and return the
corresponding <ctype> object.
It can also be used on 'cdata' instance to get its C type.
"""
if isinstance(cdecl, basestring):
return self._typeof(cdecl)
if isinstance(cdecl, self.CData):
return self._backend.typeof(cdecl)
if isinstance(cdecl, types.BuiltinFunctionType):
res = _builtin_function_type(cdecl)
if res is not None:
return res
if (isinstance(cdecl, types.FunctionType)
and hasattr(cdecl, '_cffi_base_type')):
with self._lock:
return self._get_cached_btype(cdecl._cffi_base_type)
raise TypeError(type(cdecl))
def typeof(self, cdecl):
"""Parse the C type given as a string and return the
corresponding <ctype> object.
It can also be used on 'cdata' instance to get its C type.
"""
if isinstance(cdecl, basestring):
return self._typeof(cdecl)
if isinstance(cdecl, self.CData):
return self._backend.typeof(cdecl)
if isinstance(cdecl, types.BuiltinFunctionType):
res = _builtin_function_type(cdecl)
if res is not None:
return res
if (isinstance(cdecl, types.FunctionType)
and hasattr(cdecl, '_cffi_base_type')):
with self._lock:
return self._get_cached_btype(cdecl._cffi_base_type)
raise TypeError(type(cdecl))
def typeof(self, cdecl):
"""Parse the C type given as a string and return the
corresponding <ctype> object.
It can also be used on 'cdata' instance to get its C type.
"""
if isinstance(cdecl, basestring):
return self._typeof(cdecl)
if isinstance(cdecl, self.CData):
return self._backend.typeof(cdecl)
if isinstance(cdecl, types.BuiltinFunctionType):
res = _builtin_function_type(cdecl)
if res is not None:
return res
if (isinstance(cdecl, types.FunctionType)
and hasattr(cdecl, '_cffi_base_type')):
with self._lock:
return self._get_cached_btype(cdecl._cffi_base_type)
raise TypeError(type(cdecl))
def typeof(self, cdecl):
"""Parse the C type given as a string and return the
corresponding <ctype> object.
It can also be used on 'cdata' instance to get its C type.
"""
if isinstance(cdecl, basestring):
return self._typeof(cdecl)
if isinstance(cdecl, self.CData):
return self._backend.typeof(cdecl)
if isinstance(cdecl, types.BuiltinFunctionType):
res = _builtin_function_type(cdecl)
if res is not None:
return res
if (isinstance(cdecl, types.FunctionType)
and hasattr(cdecl, '_cffi_base_type')):
with self._lock:
return self._get_cached_btype(cdecl._cffi_base_type)
raise TypeError(type(cdecl))
def inline_args(f):
# print '@@', f.__name__, type(f), isinstance(f, types.FunctionType), isinstance(f, types.TypeType), isinstance(f, types.BuiltinFunctionType)
if isinstance(f, types.FunctionType):
@functools.wraps(f)
def _f_func(self, args):
return f(self, *args)
return _f_func
elif isinstance(f, (type, types.BuiltinFunctionType)):
@functools.wraps(f)
def _f_builtin(_self, args):
return f(*args)
return _f_builtin
elif isinstance(f, types.MethodType):
@functools.wraps(f.__func__)
def _f(self, args):
return f.__func__(self, *args)
return _f
else:
@functools.wraps(f.__call__.__func__)
def _f(self, args):
return f.__call__.__func__(self, *args)
return _f
def typeof(self, cdecl):
"""Parse the C type given as a string and return the
corresponding <ctype> object.
It can also be used on 'cdata' instance to get its C type.
"""
if isinstance(cdecl, basestring):
return self._typeof(cdecl)
if isinstance(cdecl, self.CData):
return self._backend.typeof(cdecl)
if isinstance(cdecl, types.BuiltinFunctionType):
res = _builtin_function_type(cdecl)
if res is not None:
return res
if (isinstance(cdecl, types.FunctionType)
and hasattr(cdecl, '_cffi_base_type')):
with self._lock:
return self._get_cached_btype(cdecl._cffi_base_type)
raise TypeError(type(cdecl))
def get_type_hint(stmt):
try:
ns = {'file_target': file_target, 'sos_targets': sos_targets,
'path': path, 'paths': paths}
# let us grab the part before =
exec(stmt.split('=', 1)[0], ns)
# if it can compile, it can be typetrait, or something like
#
# python: input='a'
#
# where input is recognied
#
if '__annotations__' in ns and all(not isinstance(x, types.BuiltinFunctionType) and callable(x) for x in ns['__annotations__'].values()):
return ns.popitem()[1]
return None
except:
# if cannot compile, not type hint
#
# python: args='whatever'
return None
def inspect_callable(obj):
if type(obj) in (types.FunctionType, types.BuiltinFunctionType):
return Callable(obj)
if type(obj) == type:
return Callable(obj, init=True)
if type(obj) == types.MethodType:
return Callable(obj.__func__, self_obj=obj.__self__)
if type(obj) == MethodWrapperType:
return Callable(
getattr(obj.__objclass__, obj.__name__),
self_obj=obj.__self__)
if type(obj) == WrapperDescriptorType:
return Callable(obj)
if hasattr(obj, '__call__'):
return inspect_callable(obj.__call__)
raise AttributeError
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 isbuiltin(object):
"""Return true if the object is a built-in function or method.
Built-in functions and methods provide these attributes:
__doc__ documentation string
__name__ original name of this function or method
__self__ instance to which a method is bound, or None"""
return isinstance(object, types.BuiltinFunctionType)
def wrap( wrappee ):
"""Wrap the given object, module or function in a Python wrapper."""
if isinstance( wrappee, types.BuiltinFunctionType ):
return _ProfileWrapFunction( wrappee )
else:
return _ProfileWrapObject( wrappee )
def isbuiltin(object):
"""Return true if the object is a built-in function or method.
Built-in functions and methods provide these attributes:
__doc__ documentation string
__name__ original name of this function or method
__self__ instance to which a method is bound, or None"""
return isinstance(object, types.BuiltinFunctionType)
def collect_signatures(self, val):
doc = val.__doc__
type_obj = None
if isinstance(val, type) or isinstance(val, _OldClassType):
type_obj = val
val = val.__init__
try:
args, vargs, varkw, defaults = inspect.getargspec(val)
except TypeError:
# we're not doing inspect on a Python function...
if sys.platform == 'cli':
if type_obj is not None:
clr_type = clr.GetClrType(type_obj)
ctors = clr_type.GetConstructors()
return [self.get_ipy_sig(type_obj, ctor) for ctor in ctors]
elif type(val) is types.BuiltinFunctionType:
return [self.get_ipy_sig(target, target.Targets[0]) for target in val.Overloads.Functions]
elif type(val) is builtin_method_descriptor_type:
val = PythonOps.GetBuiltinMethodDescriptorTemplate(val)
return [self.get_ipy_sig(target, target.Targets[0]) for target in val.Overloads.Functions]
raise
remove_self = type_obj is not None or (type(val) is types.MethodType and
((sys.version_info >= (3,) and val.__self__ is not None) or
(sys.version_info < (3,) and val.im_self is not None)))
if remove_self:
# remove self for instance methods and types
args = args[1:]
if defaults is not None:
defaults = [repr(default) for default in defaults]
else:
defaults = []
return [(doc, args, vargs, varkw, defaults)]
def collect_signatures(self, val):
doc = val.__doc__
type_obj = None
if isinstance(val, type) or isinstance(val, _OldClassType):
type_obj = val
val = val.__init__
try:
args, vargs, varkw, defaults = inspect.getargspec(val)
except TypeError:
# we're not doing inspect on a Python function...
if sys.platform == 'cli':
if type_obj is not None:
clr_type = clr.GetClrType(type_obj)
ctors = clr_type.GetConstructors()
return [self.get_ipy_sig(type_obj, ctor) for ctor in ctors]
elif type(val) is types.BuiltinFunctionType:
return [self.get_ipy_sig(target, target.Targets[0]) for target in val.Overloads.Functions]
elif type(val) is builtin_method_descriptor_type:
val = PythonOps.GetBuiltinMethodDescriptorTemplate(val)
return [self.get_ipy_sig(target, target.Targets[0]) for target in val.Overloads.Functions]
raise
remove_self = type_obj is not None or (type(val) is types.MethodType and
((sys.version_info >= (3,) and val.__self__ is not None) or
(sys.version_info < (3,) and val.im_self is not None)))
if remove_self:
# remove self for instance methods and types
args = args[1:]
if defaults is not None:
defaults = [repr(default) for default in defaults]
else:
defaults = []
return [(doc, args, vargs, varkw, defaults)]
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 __deepcopy__(self, memo):
retVal = self.__class__()
memo[id(self)] = retVal
for attr in dir(self):
if not attr.startswith('_'):
value = getattr(self, attr)
if not isinstance(value, (types.BuiltinFunctionType, types.FunctionType, types.MethodType)):
setattr(retVal, attr, copy.deepcopy(value, memo))
for key, value in self.items():
retVal.__setitem__(key, copy.deepcopy(value, memo))
return retVal
def trace(self, frame, event, arg):
name = frame.f_code.co_name
is_method = "self" in frame.f_locals
curr_obj = None
if is_method:
curr_obj = frame.f_locals["self"]
cls = type(curr_obj)
else:
cls = None
if event == "call":
if (cls, name) not in self.prev_call:
if is_method:
func = getattr(curr_obj, name)
else:
try:
func = frame.f_globals[name]
except:
# hack to make spark work
func = self.top_level_func
if not isinstance(func, BuiltinFunctionType):
arg_names = list(frame.f_code.co_varnames[:frame.f_code.co_argcount])
types = []
for var_name in arg_names:
var = frame.f_locals[var_name]
if isinstance(var, list):
types.append((list, type(var[0])))
else:
types.append(type(var))
print("found {}".format(func))
call = FunctionCall(cls, name, arg_names, types, func)
self.results.append(call)
self.prev_call[(cls, name)] = call
else:
print("found builtin function {}".format(func))
elif event == "return":
if (cls, name) in self.prev_call:
prev_call = self.prev_call[(cls, name)]
if not prev_call.return_type:
prev_call.set_return_type(type(arg))