我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用types.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 getFunctions(self): classes = [] functions = [] try: blacklist = BLACKLIST[self.module_name] except KeyError: blacklist = set() for name in dir(self.module): attr = getattr(self.module, name) if name in blacklist: continue if isinstance(attr, (FunctionType, BuiltinFunctionType)): functions.append(name) elif isinstance(attr, type): classes.append(name) return functions, classes
def __new__(mcls, name, bases, dictionary): settings = {} # copy all settings defined by parents unless also defined in the class being constructed for name, setting in chain(*(cls.__settings__.iteritems() for cls in bases if isinstance(cls, ConfigSectionType))): if name not in dictionary and name not in settings: settings[name] = ConfigSetting(type=setting.type, value=setting.value) for attr, value in dictionary.iteritems(): if isinstance(value, ConfigSetting): settings[attr] = value elif attr.startswith('__') or isdescriptor(value) or type(value) is BuiltinFunctionType: continue else: if type(value) is bool: data_type = datatypes.Boolean else: data_type = type(value) settings[attr] = ConfigSetting(type=data_type, value=value) dictionary.update(settings) cls = super(ConfigSectionType, mcls).__new__(mcls, name, bases, dictionary) cls.__settings__ = settings cls.__defaults__ = SaveState(cls) return cls
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 __new__(cls, expectation=None, strcmp=None, is_custom_func=False): """ Args: anything (expectation: the object you want to compare) "substring", "regex" (strcmp: the type of string comparsion) Boolean (is_custom_func: set True is object is a test function of Matcher Return: Matcher """ options = {} if is_custom_func: if isinstance(expectation, (FunctionType, BuiltinFunctionType, MethodType)): options["is_custom_func"] = True else: # Todo: customized error exception raise TypeError("[{}] is not callable".format(expectation)) if strcmp: if isinstance(expectation, (str, unicode)): if strcmp.upper() == "DEFAULT" or strcmp.upper() == "SUBSTRING": options["is_substring"] = True elif strcmp.upper() == "REGEX": options["is_regex"] = True else: raise TypeError("[{}] is not a string".format(expectation)) return Matcher(expectation, options)
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 order_attributes(attrs): constants = {} functions = {} classes = {} for key, value in attrs.items(): if isinstance(value, type(int.real)) or key in ("__abstractmethods__", "__base__", "__bases__", "__class__", "__dict__", "__dictoffset__", "__file__", "__flags__", "__itemsize__", "__module__", "__name__", "__package__", "__subclasses__", "__weakrefoffset__"): pass elif isinstance(value, (type, types.ClassType)): classes[key] = value elif isinstance(value, (types.FunctionType, types.BuiltinFunctionType, type(list.append), type(object.__init__), classmethod, staticmethod)): if not (key.startswith("__") and key.endswith("__")): functions[key] = value else: constants[key] = value constants = sorted_mapping(constants) functions = sorted_mapping(functions) classes = sorted_mapping(classes) classes_reverse = collections.OrderedDict((v, k) for k, v in classes.items()) classes_ordered = collections.OrderedDict((classes_reverse[cls], cls) for cls in order_classes(classes.values())) return collections.OrderedDict(constants.items() + functions.items() + classes_ordered.items())
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)
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 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 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 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))