我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用inspect.isroutine()。
def get_action(driver, keyword): """get action class corresponding to the keyword in the driver """ drvmod = 'ProductDrivers.' + driver drvmodobj = importlib.import_module(drvmod) drvfile_methods = inspect.getmembers(drvmodobj, inspect.isroutine) main_method = [item[1] for item in drvfile_methods if item[0] == 'main'][0] main_src = inspect.getsource(main_method) pkglstmatch = re.search(r'package_list.*=.*\[(.*)\]', main_src, re.MULTILINE | re.DOTALL) pkglst = pkglstmatch.group(1).split(',') for pkg in pkglst: pkgobj = importlib.import_module(pkg) pkgdir = os.path.dirname(pkgobj.__file__) action_modules = [pkg+'.'+name for _, name, _ in pkgutil.iter_modules([pkgdir])] action_module_objs = [importlib.import_module(action_module) for action_module in action_modules] for action_module_obj in action_module_objs: for action_class in inspect.getmembers(action_module_obj, inspect.isclass): for func_name in inspect.getmembers(action_class[1], inspect.isroutine): if keyword == func_name[0]: return action_class[1] return None
def get_containing_module(value): """ Return the name of the module containing the given value, or C{None} if the module name can't be determined. @rtype: L{DottedName} """ if inspect.ismodule(value): return DottedName(value.__name__) elif isclass(value): return DottedName(value.__module__) elif (inspect.ismethod(value) and value.im_self is not None and value.im_class is ClassType): # class method. return DottedName(value.im_self.__module__) elif inspect.ismethod(value): return DottedName(value.im_class.__module__) elif inspect.isroutine(value): module = _find_function_module(value) if module is None: return None return DottedName(module) else: return None
def document(self, object, name=None, *args): """Generate documentation for an object.""" args = (object, name) + args # 'try' clause is to attempt to handle the possibility that inspect # identifies something in a way that pydoc itself has issues handling; # think 'super' and how it is a descriptor (which raises the exception # by lacking a __name__ attribute) and an instance. if inspect.isgetsetdescriptor(object): return self.docdata(*args) if inspect.ismemberdescriptor(object): return self.docdata(*args) try: if inspect.ismodule(object): return self.docmodule(*args) if inspect.isclass(object): return self.docclass(*args) if inspect.isroutine(object): return self.docroutine(*args) except AttributeError: pass if isinstance(object, property): return self.docproperty(*args) return self.docother(*args)
def render_doc(thing, title='Python Library Documentation: %s', forceload=0): """Render text documentation, given an object or a path to an object.""" object, name = resolve(thing, forceload) desc = describe(object) module = inspect.getmodule(object) if name and '.' in name: desc += ' in ' + name[:name.rfind('.')] elif module and module is not object: desc += ' in module ' + module.__name__ if type(object) is _OLD_INSTANCE_TYPE: # If the passed object is an instance of an old-style class, # document its available methods instead of its value. object = object.__class__ elif not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isgetsetdescriptor(object) or inspect.ismemberdescriptor(object) or isinstance(object, property)): # If the passed object is a piece of data or an instance, # document its available methods instead of its value. object = type(object) desc += ' object' return title % desc + '\n\n' + text.document(object, name)
def non_removable_attrs(cls): """Returns a set of names of attributes that may not be removed. Attributes whose 'mandatory' property is True are automatically added to this set. To add additional attributes to the set, override the field _extra_non_removable_attrs in subclasses, with a set of the form {'/foo', '/bar'}. """ if cls._non_removable_attrs is None: cls._non_removable_attrs = cls._extra_non_removable_attrs.copy() if cls._api_base: fields = inspect.getmembers(cls._api_base, lambda a: not inspect.isroutine(a)) for name, field in fields: if getattr(field, 'mandatory', False): cls._non_removable_attrs.add('/%s' % name) return cls._non_removable_attrs
def __new__(cls, name, bases, clsdict): """ Equip all base-class methods with a needs_values decorator, and all non-const methods with a set_dirty_and_flush_changes decorator in addition to that.""" kmm = '_mutating_methods_' if kmm in clsdict: mutating_methods = clsdict[kmm] for base in bases: methods = (t for t in inspect.getmembers(base, inspect.isroutine) if not t[0].startswith("_")) for name, method in methods: if name in clsdict: continue method_with_values = needs_values(method) if name in mutating_methods: method_with_values = set_dirty_and_flush_changes(method_with_values) # END mutating methods handling clsdict[name] = method_with_values # END for each name/method pair # END for each base # END if mutating methods configuration is set new_type = super(MetaParserBuilder, cls).__new__(cls, name, bases, clsdict) return new_type
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 render_doc(thing, title='Python Library Documentation: %s', forceload=0, renderer=None): """Render text documentation, given an object or a path to an object.""" if renderer is None: renderer = text object, name = resolve(thing, forceload) desc = describe(object) module = inspect.getmodule(object) if name and '.' in name: desc += ' in ' + name[:name.rfind('.')] elif module and module is not object: desc += ' in module ' + module.__name__ if not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isgetsetdescriptor(object) or inspect.ismemberdescriptor(object) or isinstance(object, property)): # If the passed object is a piece of data or an instance, # document its available methods instead of its value. object = type(object) desc += ' object' return title % desc + '\n\n' + renderer.document(object, name)
def _get_handlers(self, args, kwargs): '''Implement handler matching on arguments for set_handlers and remove_handlers. ''' for object in args: if inspect.isroutine(object): # Single magically named function name = object.__name__ if name not in self.event_types: raise EventException('Unknown event "%s"' % name) yield name, object else: # Single instance with magically named methods for name in dir(object): if name in self.event_types: yield name, getattr(object, name) for name, handler in kwargs.items(): # Function for handling given event (no magic) if name not in self.event_types: raise EventException('Unknown event "%s"' % name) yield name, handler
def UsageString(component, trace=None, verbose=False): """Returns a string showing how to use the component as a Fire command.""" command = trace.GetCommand() + ' ' if trace else '' if inspect.isroutine(component) or inspect.isclass(component): spec = inspectutils.GetFullArgSpec(component) return _UsageStringFromFullArgSpec(command, spec) if isinstance(component, (list, tuple)): length = len(component) if length == 0: return command if length == 1: return command + '[0]' return command + '[0..{cap}]'.format(cap=length - 1) completions = completion.Completions(component, verbose) if command: completions = [''] + completions return '\n'.join(command + end for end in completions)
def is_regular_method(klass, attr, value=None): """Test if a value of a class is regular method. example:: class MyClass(object): def to_dict(self): ... :param klass: the class :param attr: attribute name :param value: attribute value """ if value is None: value = getattr(klass, attr) assert getattr(klass, attr) == value if inspect.isroutine(value): if not is_static_method(klass, attr, value) and not is_class_method(klass, attr, value): return True return False
def is_static_method(klass, attr, value=None): """Test if a value of a class is static method. example:: class MyClass(object): @staticmethod def method(): ... :param klass: the class :param attr: attribute name :param value: attribute value """ if value is None: value = getattr(klass, attr) assert getattr(klass, attr) == value for cls in inspect.getmro(klass): if inspect.isroutine(value): if attr in cls.__dict__: binded_value = cls.__dict__[attr] if isinstance(binded_value, staticmethod): return True return False
def is_class_method(klass, attr, value=None): """Test if a value of a class is class method. example:: class MyClass(object): @classmethod def method(cls): ... :param klass: the class :param attr: attribute name :param value: attribute value """ if value is None: value = getattr(klass, attr) assert getattr(klass, attr) == value for cls in inspect.getmro(klass): if inspect.isroutine(value): if attr in cls.__dict__: binded_value = cls.__dict__[attr] if isinstance(binded_value, classmethod): return True return False
def __getattr__(self, key): # evaluate nested format-string parameters, update format results value, lastValue = super(paramDict, self).__getitem__(key), None while id(lastValue) != id(value): lastValue = value if isinstance(value, str): if value in self and value != key: value = getattr(self, value) elif reFormatString.search(value): value = value %self elif (inspect.isroutine(value) and not isinstance(value, IgnoreFunc)): value = value(self) self[key] = value return value ################################################## class Permutation
def update(self, v): """Add `v` to the hash, recursively if needed.""" self.md5.update(to_bytes(str(type(v)))) if isinstance(v, string_class): self.md5.update(to_bytes(v)) elif isinstance(v, (int, float)): self.update(str(v)) elif isinstance(v, (tuple, list)): for e in v: self.update(e) elif isinstance(v, dict): keys = v.keys() for k in sorted(keys): self.update(k) self.update(v[k]) else: for k in dir(v): if k.startswith('__'): continue a = getattr(v, k) if inspect.isroutine(a): continue self.update(k) self.update(a)
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 _get_handlers(self, args, kwargs): '''Implement handler matching on arguments for set_handlers and remove_handlers. ''' for object in args: if inspect.isroutine(object): # Single magically named function name = object.__name__ if name not in self.event_types: raise EventException('Unknown event "%s"' % name) yield name, object else: # Single instance with magically named methods for name in dir(object): if name in self.event_types: yield name, getattr(object, name) for name, handler in list(kwargs.items()): # Function for handling given event (no magic) if name not in self.event_types: raise EventException('Unknown event "%s"' % name) yield name, handler
def _object_attributes(obj, parent): attributes = {} for name in dir(obj): if name == 'None': continue try: child = getattr(obj, name) except AttributeError: # descriptors are allowed to raise AttributeError # even if they are in dir() continue pyobject = None if inspect.isclass(child): pyobject = BuiltinClass(child, {}, parent=parent) elif inspect.isroutine(child): pyobject = BuiltinFunction(builtin=child, parent=parent) else: pyobject = BuiltinUnknown(builtin=child) attributes[name] = BuiltinName(pyobject) return attributes
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 isdata(object): """Check if an object is of a type that probably means it's data.""" return not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isframe(object) or inspect.istraceback(object) or inspect.iscode(object))
def get_item(item, **kwargs): """ API versioning for each OpenStack service is independent. Generically capture the public members (non-routine and non-private) of the OpenStack SDK objects. Note the lack of the modify_output decorator. Preserving the field naming allows us to reconstruct objects and orchestrate from stored items. """ _item = {} for k,v in inspect.getmembers(item, lambda a:not(inspect.isroutine(a))): if not k.startswith('_') and not k in ignore_list: _item[k] = v return sub_dict(_item)