Python inspect.isbuiltin() Examples

The following are 30 code examples of inspect.isbuiltin(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module inspect , or try the search function .
Example #1
Source File: test_inspect.py    From oss-ftp with MIT License 6 votes vote down vote up
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)) 
Example #2
Source File: _transformer.py    From hope with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: jit.py    From hope with GNU General Public License v3.0 6 votes vote down vote up
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.") 
Example #4
Source File: gen_modules_modfile.py    From fake-bpy-module with MIT License 6 votes vote down vote up
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 
Example #5
Source File: sage_autodoc.py    From pyoptools with GNU General Public License v3.0 6 votes vote down vote up
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)
            else:
                return None
        else:
            # The check above misses ordinary Python methods in Cython
            # files.
            try:
                argspec = inspect.getargspec(self.object)
            except TypeError:
                if (inspect.ismethod(self.object) and 
                    self.env.config.autodoc_builtin_argspec):
                    argspec = self.env.config.autodoc_builtin_argspec(self.object.im_func)
                else:
                    return None
        if argspec[0] and argspec[0][0] in ('cls', 'self'):
            del argspec[0][0]
        return inspect.formatargspec(*argspec) 
Example #6
Source File: sage_autodoc.py    From pyoptools with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #7
Source File: test_inspect.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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)) 
Example #8
Source File: test_inspect.py    From BinderFilter with MIT License 6 votes vote down vote up
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)) 
Example #9
Source File: test_inspect.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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)) 
Example #10
Source File: response.py    From python-ddd with MIT License 6 votes vote down vote up
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 
Example #11
Source File: nvmarker.py    From pyprof2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #12
Source File: namenode.py    From petastorm with Apache License 2.0 6 votes vote down vote up
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 
Example #13
Source File: langhelpers.py    From planespotter with MIT License 5 votes vote down vote up
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) 
Example #14
Source File: pydoc.py    From Imogen with MIT License 5 votes vote down vote up
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__ 
Example #15
Source File: core.py    From scales with MIT License 5 votes vote down vote up
def _BuildServiceProxy(Iface):
    """Build a proxy class that intercepts all user methods on [Iface]
    and routes them to a message dispatcher.

    Args:
      Iface - An interface to proxy
    """
    def ProxyMethod(method_name, orig_method, asynchronous=False):
      @functools.wraps(orig_method)
      def _ProxyMethod(self, *args, **kwargs):
        ar = self._dispatcher.DispatchMethodCall(method_name, args, kwargs)
        return ar if asynchronous else ar.get()
      return _ProxyMethod

    def is_user_method(m):
      return ((inspect.ismethod(m) or inspect.isfunction(m))
              and not inspect.isbuiltin(m)
              and not ClientProxyBuilder._method_name(m).startswith('__')
              and not ClientProxyBuilder._method_name(m).endswith('__'))

    # Get all methods defined on the interface.
    iface_methods = { m[0]: ProxyMethod(*m)
                      for m in inspect.getmembers(Iface, is_user_method) }
    iface_methods.pop('__init__', None)
    iface_methods.update({ m[0] + "_async": ProxyMethod(*m, asynchronous=True)
                           for m in inspect.getmembers(Iface, is_user_method) })

    # Create a proxy class to intercept the interface's methods.
    proxy = type(
      '_ScalesTransparentProxy<%s>' % Iface.__module__,
      (_ProxyBase, Iface),
      iface_methods)
    return proxy 
Example #16
Source File: generate_rsts.py    From gxpy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _is_some_method(obj):
    return (inspect.isfunction(obj) or
            inspect.ismethod(obj) or
            inspect.isbuiltin(obj) or
            inspect.ismethoddescriptor(obj)) 
Example #17
Source File: langhelpers.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #18
Source File: pretty.py    From Jacinle with MIT License 5 votes vote down vote up
def default(self, obj):
        if hasattr(obj, '__jsonify__'):
            json_object = obj.__jsonify__()
            if isinstance(json_object, six.string_types):
                return json_object
            return self.encode(json_object)
        else:
            raise TypeError("Object of type '%s' is not JSON serializable." % obj.__class__.__name__)

        if 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 
Example #19
Source File: loader.py    From pop with Apache License 2.0 5 votes vote down vote up
def prep_loaded_mod(this_sub, mod, mod_name, contracts):
    '''
    Read the attributes of a python module and create a LoadedMod, which resolves
    aliases and omits objects that should not be exposed.
    '''
    # pylint: disable=protected-access
    lmod = LoadedMod(mod_name)
    ref = f'{this_sub._subname}.{mod_name}'  # getattr(hub, ref) should resolve to this module
    for attr in getattr(mod, '__load__', dir(mod)):
        name = getattr(mod, '__func_alias__', {}).get(attr, attr)
        func = getattr(mod, attr)
        if not this_sub._omit_vars:
            if not inspect.isfunction(func) and not inspect.isclass(func) and \
                    type(func).__name__ != 'cython_function_or_method':
                lmod._vars[name] = func
                lmod._attrs[name] = func
                continue
        if attr.startswith(this_sub._omit_start):
            continue
        if attr.endswith(this_sub._omit_end):
            continue
        if inspect.isfunction(func) or inspect.isbuiltin(func) or \
                type(func).__name__ == 'cython_function_or_method':
            obj = pop.contract.Contracted(this_sub._hub, contracts, func, ref, name)
            if not this_sub._omit_func:
                if this_sub._pypath and not func.__module__.startswith(mod.__name__):
                    # We're only interested in functions defined in this module, not
                    # imported functions
                    continue
                lmod._funcs[name] = obj
                lmod._attrs[name] = obj
        else:
            klass = func
            if not this_sub._omit_class and inspect.isclass(klass):
                # We're only interested in classes defined in this module, not
                # imported classes
                if not klass.__module__.startswith(mod.__name__):
                    continue
                lmod._classes[name] = klass
                lmod._attrs[name] = klass
    return lmod 
Example #20
Source File: noseclasses.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
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") 
Example #21
Source File: pydoc.py    From Imogen with MIT License 5 votes vote down vote up
def _is_bound_method(fn):
    """
    Returns True if fn is a bound method, regardless of whether
    fn was implemented in Python or in C.
    """
    if inspect.ismethod(fn):
        return True
    if inspect.isbuiltin(fn):
        self = getattr(fn, '__self__', None)
        return not (inspect.ismodule(self) or (self is None))
    return False 
Example #22
Source File: pydoc.py    From Imogen with MIT License 5 votes vote down vote up
def _is_some_method(obj):
    return (inspect.isfunction(obj) or
            inspect.ismethod(obj) or
            inspect.isbuiltin(obj) or
            inspect.ismethoddescriptor(obj)) 
Example #23
Source File: infinite_paginator.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def _after_up_to_pad(self):
        first_after = self.number * self.page_size
        padding_length = self.pad_pages * self.page_size
        queryset = self.unfiltered_queryset[first_after:first_after + padding_length + 1]
        c = getattr(queryset, 'count', None)
        if callable(c) and not inspect.isbuiltin(c) and method_has_no_args(c):
            return c()
        return len(queryset) 
Example #24
Source File: noseclasses.py    From pySINDy with MIT License 5 votes vote down vote up
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") 
Example #25
Source File: pydoc.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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__ 
Example #26
Source File: pydoc.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def _is_bound_method(fn):
    """
    Returns True if fn is a bound method, regardless of whether
    fn was implemented in Python or in C.
    """
    if inspect.ismethod(fn):
        return True
    if inspect.isbuiltin(fn):
        self = getattr(fn, '__self__', None)
        return not (inspect.ismodule(self) or (self is None))
    return False 
Example #27
Source File: pydoc.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def _is_some_method(obj):
    return (inspect.isfunction(obj) or
            inspect.ismethod(obj) or
            inspect.isbuiltin(obj) or
            inspect.ismethoddescriptor(obj)) 
Example #28
Source File: noseclasses.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            #print '_fm C1'  # dbg
            return True
        elif inspect.isfunction(object):
            #print '_fm C2'  # dbg
            return module.__dict__ is object.__globals__
        elif inspect.isbuiltin(object):
            #print '_fm C2-1'  # dbg
            return module.__name__ == object.__module__
        elif inspect.isclass(object):
            #print '_fm C3'  # dbg
            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
            #print '_fm C3-1'  # dbg
            return module.__name__ == object.__self__.__class__.__module__
        elif inspect.getmodule(object) is not None:
            #print '_fm C4'  # dbg
            #print 'C4 mod',module,'obj',object # dbg
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            #print '_fm C5'  # dbg
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            #print '_fm C6'  # dbg
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function") 
Example #29
Source File: langhelpers.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #30
Source File: objects.py    From callee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_method(arg, min_arity=None, max_arity=None):
    """Check if argument is a method.

    Optionally, we can also check if minimum or maximum arities
    (number of accepted arguments) match given minimum and/or maximum.
    """
    if not callable(arg):
        return False

    if not any(is_(arg) for is_ in (inspect.ismethod,
                                    inspect.ismethoddescriptor,
                                    inspect.isbuiltin)):
        return False

    try:
        argnames, varargs, kwargs, defaults = getargspec(arg)
    except TypeError:
        # On CPython 2.x, built-in methods of file aren't inspectable,
        # so if it's file.read() or file.write(), we can't tell it for sure.
        # Given how this check is being used, assuming the best is probably
        # all we can do here.
        return True
    else:
        if argnames and argnames[0] == 'self':
            argnames = argnames[1:]

    if min_arity is not None:
        actual_min_arity = len(argnames) - len(defaults or ())
        assert actual_min_arity >= 0, (
            "Minimum arity of %r found to be negative (got %s)!" % (
                arg, actual_min_arity))
        if int(min_arity) != actual_min_arity:
            return False

    if max_arity is not None:
        actual_max_arity = sys.maxsize if varargs or kwargs else len(argnames)
        if int(max_arity) != actual_max_arity:
            return False

    return True