当前位置: 首页>>代码示例>>Python>>正文


Python inspect.isbuiltin方法代码示例

本文整理汇总了Python中inspect.isbuiltin方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.isbuiltin方法的具体用法?Python inspect.isbuiltin怎么用?Python inspect.isbuiltin使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在inspect的用法示例。


在下文中一共展示了inspect.isbuiltin方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_excluding_predicates

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isbuiltin [as 别名]
def test_excluding_predicates(self):
        self.istest(inspect.isbuiltin, 'sys.exit')
        self.istest(inspect.isbuiltin, '[].append')
        self.istest(inspect.iscode, 'mod.spam.func_code')
        self.istest(inspect.isframe, 'tb.tb_frame')
        self.istest(inspect.isfunction, 'mod.spam')
        self.istest(inspect.ismethod, 'mod.StupidGit.abuse')
        self.istest(inspect.ismethod, 'git.argue')
        self.istest(inspect.ismodule, 'mod')
        self.istest(inspect.istraceback, 'tb')
        self.istest(inspect.isdatadescriptor, '__builtin__.file.closed')
        self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace')
        self.istest(inspect.isgenerator, '(x for x in xrange(2))')
        self.istest(inspect.isgeneratorfunction, 'generator_function_example')
        if hasattr(types, 'GetSetDescriptorType'):
            self.istest(inspect.isgetsetdescriptor,
                        'type(tb.tb_frame).f_locals')
        else:
            self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
        if hasattr(types, 'MemberDescriptorType'):
            self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days')
        else:
            self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days)) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:25,代码来源:test_inspect.py

示例2: analyze_function

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isbuiltin [as 别名]
def analyze_function(module_name: str, function, is_method=False) -> Dict:
    function_def = {
        "name": function[0],
        "type": "method" if is_method else "function",
        "return": {
            "type": "return",
        }
    }
    if not is_method:
        function_def["module"] = module_name

    if not inspect.isbuiltin(function[1]):
        try:
            function_def["parameters"] = list(inspect.signature(function[1]).parameters.keys())
        except ValueError:
            function_def["parameters"] = []
    
    return function_def 
开发者ID:nutti,项目名称:fake-bpy-module,代码行数:20,代码来源:gen_modules_modfile.py

示例3: failover_all_class_methods

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isbuiltin [as 别名]
def failover_all_class_methods(decorator):
    """
    This decorator function wraps an entire class to decorate each member method, incl. inherited.

    Adapted from https://stackoverflow.com/a/6307868
    """

    # Convenience function to ensure `decorate` gets wrapper function attributes: name, docs, etc.
    @functools.wraps(decorator)
    def decorate(cls):
        all_methods = inspect.getmembers(cls, inspect.isbuiltin) \
            + inspect.getmembers(cls, inspect.ismethod) \
            + inspect.getmembers(cls, inspect.isroutine)
        for name, method in all_methods:
            if not name.startswith('_'):
                # It's safer to exclude all protected/private method from decoration
                setattr(cls, name, decorator(method))
        return cls

    return decorate 
开发者ID:uber,项目名称:petastorm,代码行数:22,代码来源:namenode.py

示例4: isfunc

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isbuiltin [as 别名]
def isfunc(mod, f):
	assert hasattr(mod, f)
	attr = getattr(mod, f)

	#Ignore functions like _add
	if (len(f) >= 2):
		if f[0] == "_" and f[1] != "_":
			return False

	#Ignore functions from this list
	ignore = ['__all__', '__array__', '__array_priority__', '__array_wrap__', '__bool__', '__builtins__', '__cached__', '__class__', '__deepcopy__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__file__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__index__', '__init__', '__init_subclass__', '__iter__', '__len__', '__loader__', '__module__', '__name__', '__new__', '__nonzero__', '__package__', '__path__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__setstate__', '__sizeof__', '__spec__', '__str__', '__subclasshook__', '__version__', '__weakref__']

	#Add functions to this list if they cause recursion
	ignore += ['size', 'tolist', 'dim', 'is_storage', 'item']
	if f in ignore:
		return False

	return ins.ismethod(attr) or ins.isfunction(attr) or ins.ismethoddescriptor(attr) or ins.isbuiltin(attr) 
开发者ID:adityaiitb,项目名称:pyprof2,代码行数:20,代码来源:nvmarker.py

示例5: default

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isbuiltin [as 别名]
def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat() + 'Z'
        if hasattr(obj, "to_json"):
            return self.default(obj.to_json())
        elif hasattr(obj, "__dict__"):
            d = dict(
                (key, value)
                for key, value in inspect.getmembers(obj)
                if not key.startswith("_")
                and not inspect.isabstract(value)
                and not inspect.isbuiltin(value)
                and not inspect.isfunction(value)
                and not inspect.isgenerator(value)
                and not inspect.isgeneratorfunction(value)
                and not inspect.ismethod(value)
                and not inspect.ismethoddescriptor(value)
                and not inspect.isroutine(value)
            )
            return self.default(d)
        return obj 
开发者ID:Ermlab,项目名称:python-ddd,代码行数:23,代码来源:response.py

示例6: format_args

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isbuiltin [as 别名]
def format_args(self):
        if inspect.isbuiltin(self.object) or \
               inspect.ismethoddescriptor(self.object):
            # can never get arguments of a C function or method unless
            # a function to do so is supplied
            if self.env.config.autodoc_builtin_argspec:
                argspec = self.env.config.autodoc_builtin_argspec(self.object)
                return inspect.formatargspec(*argspec)
            else:
                return None
        try:
            argspec = inspect.getargspec(self.object)
        except TypeError:
            # if a class should be documented as function (yay duck
            # typing) we try to use the constructor signature as function
            # signature without the first argument.
            try:
                argspec = inspect.getargspec(self.object.__new__)
            except TypeError:
                argspec = inspect.getargspec(self.object.__init__)
                if argspec[0]:
                    del argspec[0][0]
        return inspect.formatargspec(*argspec) 
开发者ID:cihologramas,项目名称:pyoptools,代码行数:25,代码来源:sage_autodoc.py

示例7: _check_state

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isbuiltin [as 别名]
def _check_state(fkt, state):
    for name in get_config_attrs():
        if name not in state or state[name] != getattr(config, name):
            raise LookupError("State is inconsistent with config. Inconsistent state key: [{0}].".format(name))
        
    if "main" not in state or "called" not in state or state["main"] != fkt.__name__:
        raise LookupError("State is inconsistent")
    
    for name, value in list((state["called"] if "called" in state else {}).items()):
        if name not in fkt.__globals__:
            #TODO: FIX! state of globals depends on the order of function in module. If called function comes later in the code we raise the error
            raise LookupError("State is inconsistent. Called function '%s' cannot be found in %s's global scope."%(name, fkt.__name__))

        glob_fkt = fkt.__globals__[name]
        if isinstance(glob_fkt, Wrapper):
            if "filename" in state and get_fkt_hash(glob_fkt.fkt) != value:
                raise LookupError("State is inconsistent. Hash(sha224) has changed")
        elif inspect.isbuiltin(glob_fkt) and hasattr(cache, str(id(glob_fkt))):
            if "filename" in state and get_fkt_hash(getattr(cache, str(id(glob_fkt)))) != value:
                raise LookupError("State is inconsistent. Hash(sha224) has changed")
        elif inspect.isfunction(glob_fkt):
            if "filename" in state and get_fkt_hash(glob_fkt) != value:
                raise LookupError("State is inconsistent. Hash(sha224) of called function '%s' has changed"%name)
        elif "filename" in state:
            raise LookupError("State is inconsistent.") 
开发者ID:jakeret,项目名称:hope,代码行数:27,代码来源:jit.py

示例8: visit_Call

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isbuiltin [as 别名]
def visit_Call(self, node):
        if (isinstance(node.func, ast.Name) and isinstance(node.func.ctx, ast.Load)):
            called_fkt = self.namespace[node.func.id]
            if (inspect.isbuiltin(called_fkt) or called_fkt.__name__ == "_hope_callback") and hasattr(cache, str(id(called_fkt))):
                called_fkt = getattr(cache, str(id(called_fkt)))
            elif not inspect.isfunction(called_fkt):
                raise Exception("Function '{0}' not a unbound, pure python function: ({1})".format(self.fkt.__name__, ast.dump(node)))
            
            if not node.func.id in self.namespace or not inspect.isfunction(called_fkt):
                raise Exception("Function '{0}' not accessible form global scope of function: ({1})".format(self.fkt.__name__, ast.dump(node)))
            
            called_fkt_ast = get_fkt_ast(called_fkt)
            
            if called_fkt in self.stack:
                return True
            else:
                return IterableFunctionVisitor(called_fkt.__globals__, self.stack + [called_fkt]).visit(called_fkt_ast)
        elif isinstance(node.func, ast.Attribute):
            return self.visit(node.func)
        else:
            return False 
开发者ID:jakeret,项目名称:hope,代码行数:23,代码来源:_transformer.py

示例9: add_fileline_to_docstring

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isbuiltin [as 别名]
def add_fileline_to_docstring(module, incursive=True):
    """Append the definition position to each function contained in module.

    Examples
    --------
    # Put the following codes at the end of a file
    add_fileline_to_docstring(__name__)
    """

    def _add_fileline(obj):
        """Add fileinto to a object.
        """
        if obj.__doc__ is None or 'From:' in obj.__doc__:
            return
        fname = inspect.getsourcefile(obj)
        if fname is None:
            return
        try:
            line = inspect.getsourcelines(obj)[-1]
        except IOError:
            return
        obj.__doc__ += '\n\nFrom:%s:%d' % (fname, line)

    if isinstance(module, str):
        module = sys.modules[module]
    for _, obj in inspect.getmembers(module):
        if inspect.isbuiltin(obj):
            continue
        if inspect.isfunction(obj):
            _add_fileline(obj)
        if inspect.ismethod(obj):
            _add_fileline(obj.__func__)
        if inspect.isclass(obj) and incursive:
            add_fileline_to_docstring(obj, False) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:36,代码来源:base.py

示例10: __getattr__

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isbuiltin [as 别名]
def __getattr__(self, name):
    """Inject the client id into Bullet functions."""
    attribute = getattr(pybullet, name)
    if inspect.isbuiltin(attribute):
      if name not in [
          "invertTransform", "multiplyTransforms", "getMatrixFromQuaternion",
          "getEulerFromQuaternion", "computeViewMatrixFromYawPitchRoll",
          "computeProjectionMatrixFOV", "getQuaternionFromEuler",
      ]:  # A temporary hack for now.
        attribute = functools.partial(attribute, physicsClientId=self._client)
    return attribute 
开发者ID:utra-robosoccer,项目名称:soccer-matlab,代码行数:13,代码来源:bullet_client.py

示例11: __getattr__

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isbuiltin [as 别名]
def __getattr__(self, name):
    """Inject the client id into Bullet functions."""
    attribute = getattr(pybullet, name)
    if inspect.isbuiltin(attribute):
        attribute = functools.partial(attribute, physicsClientId=self._client)
    return attribute 
开发者ID:utra-robosoccer,项目名称:soccer-matlab,代码行数:8,代码来源:bullet_client.py

示例12: _is_some_method

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isbuiltin [as 别名]
def _is_some_method(obj):
    return (inspect.isfunction(obj) or
            inspect.ismethod(obj) or
            inspect.isbuiltin(obj) or
            inspect.ismethoddescriptor(obj)) 
开发者ID:war-and-code,项目名称:jawfish,代码行数:7,代码来源:pydoc.py

示例13: describe

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isbuiltin [as 别名]
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__
    return type(thing).__name__ 
开发者ID:war-and-code,项目名称:jawfish,代码行数:28,代码来源:pydoc.py

示例14: _from_module

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isbuiltin [as 别名]
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.isfunction(object):
            return module.__dict__ is object.__globals__
        elif inspect.isbuiltin(object):
            return module.__name__ == object.__module__
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif inspect.ismethod(object):
            # This one may be a bug in cython that fails to correctly set the
            # __module__ attribute of methods, but since the same error is easy
            # to make by extension code writers, having this safety in place
            # isn't such a bad idea
            return module.__name__ == object.__self__.__class__.__module__
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True  # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function") 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:29,代码来源:noseclasses.py

示例15: get_callable_argspec

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isbuiltin [as 别名]
def get_callable_argspec(fn, no_self=False, _is_init=False):
    """Return the argument signature for any callable.

    All pure-Python callables are accepted, including
    functions, methods, classes, objects with __call__;
    builtins and other edge cases like functools.partial() objects
    raise a TypeError.

    """
    if inspect.isbuiltin(fn):
        raise TypeError("Can't inspect builtin: %s" % fn)
    elif inspect.isfunction(fn):
        if _is_init and no_self:
            spec = compat.inspect_getargspec(fn)
            return compat.ArgSpec(spec.args[1:], spec.varargs,
                                  spec.keywords, spec.defaults)
        else:
            return compat.inspect_getargspec(fn)
    elif inspect.ismethod(fn):
        if no_self and (_is_init or fn.__self__):
            spec = compat.inspect_getargspec(fn.__func__)
            return compat.ArgSpec(spec.args[1:], spec.varargs,
                                  spec.keywords, spec.defaults)
        else:
            return compat.inspect_getargspec(fn.__func__)
    elif inspect.isclass(fn):
        return get_callable_argspec(
            fn.__init__, no_self=no_self, _is_init=True)
    elif hasattr(fn, '__func__'):
        return compat.inspect_getargspec(fn.__func__)
    elif hasattr(fn, '__call__'):
        if inspect.ismethod(fn.__call__):
            return get_callable_argspec(fn.__call__, no_self=no_self)
        else:
            raise TypeError("Can't inspect callable: %s" % fn)
    else:
        raise TypeError("Can't inspect callable: %s" % fn) 
开发者ID:jpush,项目名称:jbox,代码行数:39,代码来源:langhelpers.py


注:本文中的inspect.isbuiltin方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。