Python inspect.ismethoddescriptor() Examples

The following are 30 code examples of inspect.ismethoddescriptor(). 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: 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 #2
Source File: python.py    From darkc0de-old-stuff with GNU General Public License v3.0 6 votes vote down vote up
def getMethods(self, object, class_name):
        try:
            key = "%s:%s" % (self.module_name, class_name)
            blacklist = BLACKLIST[key]
        except KeyError:
            blacklist = set()
        methods = []
        for name in dir(object):
            if name in blacklist:
                continue
            if SKIP_PRIVATE and name.startswith("__"):
                continue
            attr = getattr(object, name)
            if not ismethoddescriptor(attr):
                continue
            methods.append(name)
        return methods 
Example #3
Source File: typechecker.py    From pytypes with Apache License 2.0 6 votes vote down vote up
def auto_override_class(cls, force = False, force_recursive = False):
    """Works like auto_override, but is only applicable to classes.
    """
    if not pytypes.checking_enabled:
        return cls
    assert(isclass(cls))
    if not force and is_no_type_check(cls):
        return cls
    # To play it safe we avoid to modify the dict while iterating over it,
    # so we previously cache keys.
    # For this we don't use keys() because of Python 3.
    # Todo: Better use inspect.getmembers here
    keys = [key for key in cls.__dict__]
    for key in keys:
        memb = cls.__dict__[key]
        if force_recursive or not is_no_type_check(memb):
            if isfunction(memb) or ismethod(memb) or ismethoddescriptor(memb):
                if util._has_base_method(memb, cls):
                    setattr(cls, key, override(memb))
            elif isclass(memb):
                auto_override_class(memb, force_recursive, force_recursive)
    return cls 
Example #4
Source File: python.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def get_func_args(func, stripself=False):
    """Return the argument name list of a callable"""
    if inspect.isfunction(func):
        func_args, _, _, _ = _getargspec_py23(func)
    elif inspect.isclass(func):
        return get_func_args(func.__init__, True)
    elif inspect.ismethod(func):
        return get_func_args(func.__func__, True)
    elif inspect.ismethoddescriptor(func):
        return []
    elif isinstance(func, partial):
        return [x for x in get_func_args(func.func)[len(func.args):]
                if not (func.keywords and x in func.keywords)]
    elif hasattr(func, '__call__'):
        if inspect.isroutine(func):
            return []
        elif getattr(func, '__name__', None) == '__call__':
            return []
        else:
            return get_func_args(func.__call__, True)
    else:
        raise TypeError('%s is not callable' % type(func))
    if stripself:
        func_args.pop(0)
    return func_args 
Example #5
Source File: python.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def get_func_args(func, stripself=False):
    """Return the argument name list of a callable"""
    if inspect.isfunction(func):
        func_args, _, _, _ = _getargspec_py23(func)
    elif inspect.isclass(func):
        return get_func_args(func.__init__, True)
    elif inspect.ismethod(func):
        return get_func_args(func.__func__, True)
    elif inspect.ismethoddescriptor(func):
        return []
    elif isinstance(func, partial):
        return [x for x in get_func_args(func.func)[len(func.args):]
                if not (func.keywords and x in func.keywords)]
    elif hasattr(func, '__call__'):
        if inspect.isroutine(func):
            return []
        elif getattr(func, '__name__', None) == '__call__':
            return []
        else:
            return get_func_args(func.__call__, True)
    else:
        raise TypeError('%s is not callable' % type(func))
    if stripself:
        func_args.pop(0)
    return func_args 
Example #6
Source File: nvmarker.py    From apex 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 #7
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 #8
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 #9
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 #10
Source File: pydoc.py    From jawfish 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 #11
Source File: pydoc.py    From unity-python with MIT License 5 votes vote down vote up
def _is_some_method(obj):
    return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj) 
Example #12
Source File: mypydoc.py    From azure-linux-extensions with Apache License 2.0 5 votes vote down vote up
def _is_some_method(obj):
    return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj) 
Example #13
Source File: pydoc.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def _is_some_method(obj):
    return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj) 
Example #14
Source File: pydoc.py    From android_universal 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 #15
Source File: fake.py    From CNCGToolKit with MIT License 5 votes vote down vote up
def is_class_instance(obj):
    """Like inspect.* methods."""
    return not (inspect.isclass(obj) or inspect.ismodule(obj)
                or inspect.isbuiltin(obj) or inspect.ismethod(obj)
                or inspect.ismethoddescriptor(obj) or inspect.iscode(obj)
                or inspect.isgenerator(obj)) 
Example #16
Source File: pydoc.py    From RevitBatchProcessor with GNU General Public License v3.0 5 votes vote down vote up
def _is_some_method(obj):
    return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj) 
Example #17
Source File: test_config.py    From gdata-python3 with Apache License 2.0 5 votes vote down vote up
def check_data_classes(test, classes):
    import inspect
    for data_class in classes:
        test.assertTrue(data_class.__doc__ is not None,
                        'The class %s should have a docstring' % data_class)
        if hasattr(data_class, '_qname'):
            qname_versions = None
            if isinstance(data_class._qname, tuple):
                qname_versions = data_class._qname
            else:
                qname_versions = (data_class._qname,)
            for versioned_qname in qname_versions:
                test.assertTrue(isinstance(versioned_qname, str),
                                'The class %s has a non-string _qname' % data_class)
                test.assertTrue(not versioned_qname.endswith('}'),
                                'The _qname for class %s is only a namespace' % (
                                    data_class))

        for attribute_name, value in data_class.__dict__.items():
            # Ignore all elements that start with _ (private members)
            if not attribute_name.startswith('_'):
                try:
                    if not (isinstance(value, str) or inspect.isfunction(value)
                            or (isinstance(value, list)
                                and issubclass(value[0], atom.core.XmlElement))
                            or type(value) == property  # Allow properties.
                            or inspect.ismethod(value)  # Allow methods.
                            or inspect.ismethoddescriptor(value)  # Allow method descriptors.
                            # staticmethod et al.
                            or issubclass(value, atom.core.XmlElement)):
                        test.fail(
                            'XmlElement member should have an attribute, XML class,'
                            ' or list of XML classes as attributes.')

                except TypeError:
                    test.fail('Element %s in %s was of type %s' % (
                        attribute_name, data_class._qname, type(value))) 
Example #18
Source File: __init__.py    From pdoc with GNU Affero General Public License v3.0 5 votes vote down vote up
def _is_descriptor(obj):
    return (inspect.isdatadescriptor(obj) or
            inspect.ismethoddescriptor(obj) or
            inspect.isgetsetdescriptor(obj) or
            inspect.ismemberdescriptor(obj)) 
Example #19
Source File: docscrape.py    From brian2genn with GNU General Public License v2.0 5 votes vote down vote up
def methods(self):
        if self._cls is None:
            return [] 
        methods = [name for name, func in iteritems(getattr(self._cls, '__dict__'))
                   if ((not name.startswith('_')
                        or name in self.extra_public_methods)
                       and ((callable(func) and not isinstance(func, type)) or
                            inspect.ismethoddescriptor(func)))]
        return methods 
Example #20
Source File: pydoc.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def _is_some_method(obj):
    return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj) 
Example #21
Source File: test_inspect.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_getmembers_descriptors(self):
        class A(object):
            dd = _BrokenDataDescriptor()
            md = _BrokenMethodDescriptor()

        def pred_wrapper(pred):
            # A quick'n'dirty way to discard standard attributes of new-style
            # classes.
            class Empty(object):
                pass
            def wrapped(x):
                if '__name__' in dir(x) and hasattr(Empty, x.__name__):
                    return False
                return pred(x)
            return wrapped

        ismethoddescriptor = pred_wrapper(inspect.ismethoddescriptor)
        isdatadescriptor = pred_wrapper(inspect.isdatadescriptor)

        self.assertEqual(inspect.getmembers(A, ismethoddescriptor),
            [('md', A.__dict__['md'])])
        self.assertEqual(inspect.getmembers(A, isdatadescriptor),
            [('dd', A.__dict__['dd'])])

        class B(A):
            pass

        self.assertEqual(inspect.getmembers(B, ismethoddescriptor),
            [('md', A.__dict__['md'])])
        self.assertEqual(inspect.getmembers(B, isdatadescriptor),
            [('dd', A.__dict__['dd'])]) 
Example #22
Source File: doctest.py    From Project-New-Reign---Nemesis-Main 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:
            return True
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif inspect.isfunction(object):
            return module.__dict__ is object.__globals__
        elif inspect.ismethoddescriptor(object):
            if hasattr(object, '__objclass__'):
                obj_mod = object.__objclass__.__module__
            elif hasattr(object, '__module__'):
                obj_mod = object.__module__
            else:
                return True # [XX] no easy way to tell otherwise
            return module.__name__ == obj_mod
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        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 #23
Source File: pydoc.py    From Project-New-Reign---Nemesis-Main 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 #24
Source File: test_config.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def check_data_classes(test, classes):
  import inspect
  for data_class in classes:
    test.assert_(data_class.__doc__ is not None,
                 'The class %s should have a docstring' % data_class)
    if hasattr(data_class, '_qname'):
      qname_versions = None
      if isinstance(data_class._qname, tuple):
        qname_versions = data_class._qname
      else:
        qname_versions = (data_class._qname,)
      for versioned_qname in qname_versions:
        test.assert_(isinstance(versioned_qname, str),
                     'The class %s has a non-string _qname' % data_class)
        test.assert_(not versioned_qname.endswith('}'), 
                     'The _qname for class %s is only a namespace' % (
                         data_class))

    for attribute_name, value in data_class.__dict__.items():
      # Ignore all elements that start with _ (private members)
      if not attribute_name.startswith('_'):
        try:
          if not (isinstance(value, str) or inspect.isfunction(value) 
              or (isinstance(value, list)
                  and issubclass(value[0], atom.core.XmlElement))
              or type(value) == property # Allow properties.
              or inspect.ismethod(value) # Allow methods. 
              or inspect.ismethoddescriptor(value) # Allow method descriptors.
                                                   # staticmethod et al.
              or issubclass(value, atom.core.XmlElement)):
            test.fail(
                'XmlElement member should have an attribute, XML class,'
                ' or list of XML classes as attributes.')

        except TypeError:
          test.fail('Element %s in %s was of type %s' % (
              attribute_name, data_class._qname, type(value))) 
Example #25
Source File: fuzz_core_test.py    From CrossHair with MIT License 5 votes vote down vote up
def run_class_method_trials(self, cls: Type, min_trials: int) -> None:
        debug('Checking class', cls)
        for method_name, method in list(inspect.getmembers(cls)):
            # We expect some methods to be different (at least, for now):
            if method_name.startswith('__'):
                continue
            if method_name.startswith('_c_'):  # Leftovers from forbiddenfruit curses
                continue
            if not (inspect.isfunction(method) or inspect.ismethoddescriptor(method)):
                continue
            sig = resolve_signature(method)
            if sig is None:
                continue
            debug('Checking method', method_name)
            num_trials = min_trials # TODO: something like this?:  min_trials + round(len(sig.parameters) ** 1.5)
            arg_names = [chr(ord('a') + i - 1) for i in range(1, len(sig.parameters))]
            # TODO: some methods take kw-only args (list.sort for example):
            expr_str = 'self.' + method_name + '(' + ','.join(arg_names) + ')'
            arg_type_roots = {name: object for name in arg_names}
            arg_type_roots['self'] = cls
            num_unsupported = 0
            for trial_num in range(num_trials):
                status = self.run_trial(expr_str, arg_type_roots, f'{method_name} #{trial_num}')
                if status is TrialStatus.UNSUPPORTED:
                    num_unsupported += 1
            if num_unsupported == num_trials:
                self.fail(f'{num_unsupported} unsupported cases out of {num_trials} testing the method "{method_name}"') 
Example #26
Source File: fake.py    From python-tools with MIT License 5 votes vote down vote up
def is_class_instance(obj):
    """Like inspect.* methods."""
    return not (inspect.isclass(obj) or inspect.ismodule(obj)
                or inspect.isbuiltin(obj) or inspect.ismethod(obj)
                or inspect.ismethoddescriptor(obj) or inspect.iscode(obj)
                or inspect.isgenerator(obj)) 
Example #27
Source File: __init__.py    From python-tools with MIT License 5 votes vote down vote up
def type(self):
        """Imitate the tree.Node.type values."""
        cls = self._cls().obj
        if inspect.isclass(cls):
            return 'classdef'
        elif inspect.ismodule(cls):
            return 'file_input'
        elif inspect.isbuiltin(cls) or inspect.ismethod(cls) \
                or inspect.ismethoddescriptor(cls):
            return 'funcdef' 
Example #28
Source File: __init__.py    From python-tools with MIT License 5 votes vote down vote up
def api_type(self):
        if fake.is_class_instance(self.obj):
            return 'instance'

        cls = self._cls().obj
        if inspect.isclass(cls):
            return 'class'
        elif inspect.ismodule(cls):
            return 'module'
        elif inspect.isbuiltin(cls) or inspect.ismethod(cls) \
                or inspect.ismethoddescriptor(cls):
            return 'function' 
Example #29
Source File: __init__.py    From python-tools with MIT License 5 votes vote down vote up
def params(self):
        params_str, ret = self._parse_function_doc()
        tokens = params_str.split(',')
        if inspect.ismethoddescriptor(self._cls().obj):
            tokens.insert(0, 'self')
        params = []
        for p in tokens:
            parts = [FakeName(part) for part in p.strip().split('=')]
            if len(parts) > 1:
                parts.insert(1, Operator(zero_position_modifier, '=', (0, 0)))
            params.append(Param(parts, self))
        return params 
Example #30
Source File: pydoc.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def _is_some_method(obj):
    return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj)