本文整理汇总了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))
示例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
示例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
示例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)
示例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
示例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)
示例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.")
示例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
示例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)
示例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
示例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
示例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))
示例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__
示例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")
示例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)