我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用inspect.ismethoddescriptor()。
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
def default(self, obj): 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
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
def format_args(self): if inspect.isbuiltin(self.object) or \ inspect.ismethoddescriptor(self.object): # cannot introspect arguments of a C function or method return None try: argspec = getargspec(self.object) except TypeError: if (is_builtin_class_method(self.object, '__new__') and is_builtin_class_method(self.object, '__init__')): raise TypeError('%r is a builtin class' % self.object) # 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 = getargspec(self.object.__new__) except TypeError: argspec = getargspec(self.object.__init__) if argspec[0]: del argspec[0][0] args = formatargspec(*argspec) # escape backslashes for reST args = args.replace('\\', '\\\\') return args
def default(self, obj): # if hasattr(obj, "to_json"): # return self.default(obj.to_json()) if isinstance(obj, Enum): return obj.name 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) and not self.isempty(value) and not value is None ) return self.default(d) return obj
def _format_function_args(obj): if inspect.isbuiltin(obj) or \ inspect.ismethoddescriptor(obj): # cannot introspect arguments of a C function or method return None try: argspec = getargspec(obj) 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 = getargspec(obj.__new__) except TypeError: argspec = getargspec(obj.__init__) if argspec[0]: del argspec[0][0] args = inspect.formatargspec(*argspec) # escape backslashes for reST args = args.replace('\\', '\\\\') return args
def default(self, obj): if hasattr(obj, "to_json"): return self.default(obj.to_json()) elif hasattr(obj, "__dict__"): data = 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(data) return obj
def _is_some_method(obj): return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj)
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))
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
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'
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'
def params(self): params_str, ret = self._parse_function_doc() tokens = params_str.split(',') if inspect.ismethoddescriptor(self.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
def type(self): """Imitate the tree.Node.type values.""" cls = self._get_class() 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'
def _get_class(self): if not fake.is_class_instance(self.obj) or \ inspect.ismethoddescriptor(self.obj): # slots return self.obj try: return self.obj.__class__ except AttributeError: # happens with numpy.core.umath._UFUNC_API (you get it # automatically by doing `import numpy`. return type
def get_params(self): return [] # TODO Fix me. params_str, ret = self._parse_function_doc() tokens = params_str.split(',') if inspect.ismethoddescriptor(self.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('=', (0, 0))) params.append(Param(parts, self)) return params
def get_param_names(self): params_str, ret = self._parse_function_doc() tokens = params_str.split(',') if inspect.ismethoddescriptor(self.obj): tokens.insert(0, 'self') for p in tokens: parts = p.strip().split('=') if len(parts) > 1: parts.insert(1, Operator('=', (0, 0))) yield UnresolvableParamName(self, parts[0])
def api_type(self): obj = self.obj if inspect.isclass(obj): return 'class' elif inspect.ismodule(obj): return 'module' elif inspect.isbuiltin(obj) or inspect.ismethod(obj) \ or inspect.ismethoddescriptor(obj) or inspect.isfunction(obj): return 'function' # Everything else... return 'instance'
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): xname = None if '__name__' in dir(x): xname = x.__name__ elif isinstance(x, (classmethod, staticmethod)): # Some of PyPy's standard descriptors are # class/staticmethods xname = x.__func__.__name__ if xname is not None and hasattr(Empty, xname): 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'])])
def is_classmethod(meth): """Detects if the given callable is a classmethod. """ if inspect.ismethoddescriptor(meth): return isinstance(meth, classmethod) if not inspect.ismethod(meth): return False if not inspect.isclass(meth.__self__): return False if not hasattr(meth.__self__, meth.__name__): return False return meth == getattr(meth.__self__, meth.__name__)
def _has_base_method(meth, cls): meth0 = _actualfunc(meth) for cls1 in mro(cls)[1:]: if hasattr(cls1, meth0.__name__): fmeth = getattr(cls1, meth0.__name__) if inspect.isfunction(fmeth) or inspect.ismethod(fmeth) \ or inspect.ismethoddescriptor(fmeth): return True return False
def format_args(self): if inspect.isbuiltin(self.object) or \ inspect.ismethoddescriptor(self.object): # can never get arguments of a C function or method return None argspec = getargspec(self.object) if argspec[0] and argspec[0][0] in ('cls', 'self'): del argspec[0][0] args = formatargspec(*argspec) # escape backslashes for reST args = args.replace('\\', '\\\\') return args
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'])])
def _is_some_method(obj): return (inspect.isfunction(obj) or inspect.ismethod(obj) or inspect.isbuiltin(obj) or inspect.ismethoddescriptor(obj))
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")
def __get__(self, instance, owner): if inspect.ismethoddescriptor(self.value) or inspect.isdatadescriptor(self.value): return self.value.__get__(instance, owner) if inspect.isfunction(self.value): if instance is None: return self else: return six.create_bound_method(self.value, instance) else: return self.value #------------------------------------------------[ CheckedInstance ]
def arg_checks(**checks): def catch_wrapped(f): if inspect.ismethoddescriptor(f): f.__func__.arg_checks = checks else: f.arg_checks = checks @wrapt.decorator def check_call(wrapped, instance, args, kwargs): if six.PY2: if isinstance(wrapped, functools.partial) and not wrapped.func.__self__ and instance: args = (instance,)+args return ArgumentCheckedCallable(wrapped)(*args, **kwargs) return check_call(f) return catch_wrapped
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. elif inspect.ismethoddescriptor(object): # Unbound PyQt signals reach this point in Python 3.4b3, and we want # to avoid throwing an error. See also http://bugs.python.org/issue3158 return False else: raise ValueError("object must be a class or function, got %r" % object)
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)))