我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用inspect.isfunction()。
def add(self, categorize): """Add given method to categorize messages. When a message is received, each of the added methods (most recently added method first) is called with the message. The method should return a category (any hashable object) or None (in which case next recently added method is called with the same message). If all the methods return None for a given message, the message is queued with category=None, so that 'receive' method here works just as Task.receive. """ if inspect.isfunction(categorize): argspec = inspect.getargspec(categorize) if len(argspec.args) != 1: categorize = None elif type(categorize) != partial_func: categorize = None if categorize: self._categorize.insert(0, categorize) else: logger.warning('invalid categorize function ignored')
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.func_globals elif inspect.isclass(object): return module.__name__ == object.__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")
def inject(*args): if len(args) == 1 and inspect.isfunction(args[0]): return inject_function(args[0]) else: def inject_class(cls): orig_init = cls.__init__ def __init__(self, *a, **kw): container = Container() for arg in args: obj = container.get_object(arg) setattr(self, arg, obj) orig_init(self, *a, **kw) cls.__init__ = __init__ return cls return inject_class
def addWidget(self, w, name=None, scale=None): if not self.acceptsType(w): raise Exception("Widget type %s not supported by WidgetGroup" % type(w)) if name is None: name = str(w.objectName()) if name == '': raise Exception("Cannot add widget '%s' without a name." % str(w)) self.widgetList[w] = name self.scales[w] = scale self.readWidget(w) if type(w) in WidgetGroup.classes: signal = WidgetGroup.classes[type(w)][0] else: signal = w.widgetGroupInterface()[0] if signal is not None: if inspect.isfunction(signal) or inspect.ismethod(signal): signal = signal(w) signal.connect(self.mkChangeCallback(w)) else: self.uncachedWidgets[w] = None
def decorator(target): """A signature-matching decorator factory.""" def decorate(fn): if not inspect.isfunction(fn): raise Exception("not a decoratable function") spec = compat.inspect_getfullargspec(fn) names = tuple(spec[0]) + spec[1:3] + (fn.__name__,) targ_name, fn_name = _unique_symbols(names, 'target', 'fn') metadata = dict(target=targ_name, fn=fn_name) metadata.update(format_argspec_plus(spec, grouped=False)) metadata['name'] = fn.__name__ code = """\ def %(name)s(%(args)s): return %(target)s(%(fn)s, %(apply_kw)s) """ % metadata decorated = _exec_code_in_env(code, {targ_name: target, fn_name: fn}, fn.__name__) decorated.__defaults__ = getattr(fn, 'im_func', fn).__defaults__ decorated.__wrapped__ = fn return update_wrapper(decorated, fn) return update_wrapper(decorate, target)
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 func_globals(object) elif inspect.isclass(object): return module.__name__ == object.__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")
def describe(module): """ Describe the module object passed as argument including its classes and functions """ wi('[Module: %s]\n' % module.__name__) indent() count = 0 for name in dir(module): obj = getattr(module, name) if inspect.isclass(obj): count += 1; describe_klass(obj) elif (inspect.ismethod(obj) or inspect.isfunction(obj)): count +=1 ; describe_func(obj) elif inspect.isbuiltin(obj): count += 1; describe_builtin(obj) if count==0: wi('(No members)') dedent()
def register_check(check, codes=None): """Register a new check object.""" def _add_check(check, kind, codes, args): if check in _checks[kind]: _checks[kind][check][0].extend(codes or []) else: _checks[kind][check] = (codes or [''], args) if inspect.isfunction(check): args = _get_parameters(check) if args and args[0] in ('physical_line', 'logical_line'): if codes is None: codes = ERRORCODE_REGEX.findall(check.__doc__ or '') _add_check(check, args[0], codes, args) elif inspect.isclass(check): if _get_parameters(check.__init__)[:2] == ['self', 'tree']: _add_check(check, 'tree', codes, None)
def activation_str(self): """ Get printable string from activation function. :return: string """ if hasattr(self, 'activation'): if self.activation is None: return str(None) elif inspect.isclass(self.activation): return self.activation.__class__.__name__ elif inspect.isfunction(self.activation): return self.activation.__name__ else: return str(self.activation) else: return ''
def add_handlers(self, namespace): """ Add handler functions from the given `namespace`, for instance a module. The namespace may be a string, in which case it is expected to be a name of a module. It may also be a dictionary mapping names to functions. Only non-underscore-prefixed functions and methods are imported. :param namespace: Namespace object. :type namespace: str|module|dict[str, function] """ if isinstance(namespace, str): namespace = import_module(namespace) if isinstance(namespace, dict): namespace = namespace.items() else: namespace = vars(namespace).items() for name, value in namespace: if name.startswith('_'): continue if isfunction(value) or ismethod(value): self.handlers[name] = value
def add_network_methods(target): ''' Attach extension methods to an object that represents a Veneer network. Note: The 'network_' prefix will be removed from method names. target: Veneer network object to attach extension methods to. ''' import veneer.extensions as extensions # Import self to inspect available functions # Generate dict of {function name: function}, skipping this function this_func_name = sys._getframe().f_code.co_name funcs = inspect.getmembers(extensions, inspect.isfunction) funcs = dict((func_name, func) for func_name, func in funcs if func_name != this_func_name ) # Assign functions to target, removing the 'network_' prefix for f_name, f in funcs.items(): if f_name.startswith('network_'): f_name = f_name.replace('network_', '') setattr(target, f_name, MethodType(f, target))
def _get_queryset_methods(cls, queryset_class): def create_method(name, method): def manager_method(self, *args, **kwargs): return getattr(self.get_queryset(), name)(*args, **kwargs) manager_method.__name__ = method.__name__ manager_method.__doc__ = method.__doc__ return manager_method new_methods = {} # Refs http://bugs.python.org/issue1785. predicate = inspect.isfunction if six.PY3 else inspect.ismethod for name, method in inspect.getmembers(queryset_class, predicate=predicate): # Only copy missing methods. if hasattr(cls, name): continue # Only copy public methods or methods with the attribute `queryset_only=False`. queryset_only = getattr(method, 'queryset_only', None) if queryset_only or (queryset_only is None and name.startswith('_')): continue # Copy the method onto the manager. new_methods[name] = create_method(name, method) return new_methods
def __new__(cls, name, bases, attrs): get_form = attrs.get('get_form') if get_form and inspect.isfunction(get_form): try: inspect.getcallargs(get_form, None) except TypeError: warnings.warn( "`%s.%s.get_form` method must define a default value for " "its `form_class` argument." % (attrs['__module__'], name), RemovedInDjango110Warning, stacklevel=2 ) def get_form_with_form_class(self, form_class=None): if form_class is None: form_class = self.get_form_class() return get_form(self, form_class=form_class) attrs['get_form'] = get_form_with_form_class return super(FormMixinBase, cls).__new__(cls, name, bases, attrs)
def __init__(self, Class): self.uniforms = [] self.program = None self.error = 0 for key, value in Class.__dict__.items() : if key.startswith('__'): continue if inspect.ismethod(getattr(Class, key)): continue if inspect.isfunction(getattr(Class, key)): continue self.__dict__[key] = value self.uniforms.append(key) if not self.owner: from bge import logic self.owner = logic.getCurrentController().owner self.uniforms = [x for x in self.uniforms if x not in self.owner.getPropertyNames()]
def getAttrFromPython(path, classname): with open(path) as f: code = f.read() code = code.replace('import filter2D', '#') code = code.replace('from filter2D', '#') code = "class Filter2D: pass\n" + code code = compile(code, path, 'exec') myglob = dict() exec(code, dict(), myglob) attr = dict() _class = myglob[classname] for key, value in _class.__dict__.items(): if key.startswith('__'): continue if inspect.ismethod(getattr(_class, key)): continue if inspect.isfunction(getattr(_class, key)): continue attr[key]=value return attr
def getTestCaseNames(self, testCaseClass): """Override to select with selector, unless config.getTestCaseNamesCompat is True """ if self.config.getTestCaseNamesCompat: return unittest.TestLoader.getTestCaseNames(self, testCaseClass) def wanted(attr, cls=testCaseClass, sel=self.selector): item = getattr(cls, attr, None) if isfunction(item): item = unbound_method(cls, item) elif not ismethod(item): return False return sel.wantMethod(item) cases = filter(wanted, dir(testCaseClass)) # add runTest if nothing else picked if not cases and hasattr(testCaseClass, 'runTest'): cases = ['runTest'] if self.sortTestMethodsUsing: sort_list(cases, cmp_to_key(self.sortTestMethodsUsing)) return cases
def loadTestsFromTestClass(self, cls): """Load tests from a test class that is *not* a unittest.TestCase subclass. In this case, we can't depend on the class's `__init__` taking method name arguments, so we have to compose a MethodTestCase for each method in the class that looks testlike. """ def wanted(attr, cls=cls, sel=self.selector): item = getattr(cls, attr, None) if isfunction(item): item = unbound_method(cls, item) elif not ismethod(item): return False return sel.wantMethod(item) cases = [self.makeTest(getattr(cls, case), cls) for case in filter(wanted, dir(cls))] for test in self.config.plugins.loadTestsFromTestClass(cls): cases.append(test) return self.suiteClass(ContextList(cases, context=cls))
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.func_globals elif inspect.isclass(object): # Some jython classes don't set __module__ return module.__name__ == getattr(object, '__module__', None) 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")
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.func_globals 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_defining_item(self, code): for modname, mod in sys.modules.iteritems(): file = getattr(mod, '__file__', '').replace('.pyc', '.py') if file == code.co_filename: for classname,clazz in inspect.getmembers(mod, predicate=inspect.isclass): for name,member in inspect.getmembers(clazz, predicate=inspect.ismethod): filename = member.im_func.func_code.co_filename lineno = member.im_func.func_code.co_firstlineno if filename == code.co_filename and lineno == code.co_firstlineno: self.imports_.add((modname, clazz.__name__)) return clazz, member for name,member in inspect.getmembers(clazz, predicate=inspect.isfunction): filename = member.func_code.co_filename lineno = member.func_code.co_firstlineno if filename == code.co_filename and lineno == code.co_firstlineno: self.imports_.add((modname, clazz.__name__)) return clazz, member self.imports_.add((modname,)) return mod, mod
def _get_function_source(func): if _PY34: func = inspect.unwrap(func) elif hasattr(func, '__wrapped__'): func = func.__wrapped__ if inspect.isfunction(func): code = func.__code__ return (code.co_filename, code.co_firstlineno) if isinstance(func, functools.partial): return _get_function_source(func.func) if _PY34 and isinstance(func, functools.partialmethod): return _get_function_source(func.func) return None
def get_cache_key(self, *args, **kwargs): callargs = inspect.getcallargs(self.fn, *args, **kwargs) values = [] if isfunction(self.vary_on): values = self.vary_on(*args, **kwargs) else: for arg_name, attrs in self.vary_on: value = callargs[arg_name] for attr in attrs: value = getattr(value, attr) values.append(value) args_string = ','.join(self._serialize_for_key(value) for value in values) if len(args_string) > 150: args_string = 'H' + self._hash(args_string) return 'quickcache.{}/{}'.format(self.prefix, args_string)
def get_callable_name(function): """Generate a name from callable. Tries to do the best to guess fully qualified callable name. """ method_self = get_method_self(function) if method_self is not None: # This is a bound method. if isinstance(method_self, six.class_types): # This is a bound class method. im_class = method_self else: im_class = type(method_self) try: parts = (im_class.__module__, function.__qualname__) except AttributeError: parts = (im_class.__module__, im_class.__name__, function.__name__) elif inspect.ismethod(function) or inspect.isfunction(function): # This could be a function, a static method, a unbound method... try: parts = (function.__module__, function.__qualname__) except AttributeError: if hasattr(function, 'im_class'): # This is a unbound method, which exists only in python 2.x im_class = function.im_class parts = (im_class.__module__, im_class.__name__, function.__name__) else: parts = (function.__module__, function.__name__) else: im_class = type(function) if im_class is _TYPE_TYPE: im_class = function try: parts = (im_class.__module__, im_class.__qualname__) except AttributeError: parts = (im_class.__module__, im_class.__name__) return '.'.join(parts)
def get_matching_classes(self, loadable_class_names): """Get loadable classes from a list of names. Each name can be a full module path or the full path to a method that returns classes to use. The latter behavior is useful to specify a method that returns a list of classes to use in a default case. """ classes = [] for cls_name in loadable_class_names: obj = importutils.import_class(cls_name) if self._is_correct_class(obj): classes.append(obj) elif inspect.isfunction(obj): # Get list of classes from a function for cls in obj(): classes.append(cls) else: error_str = 'Not a class of the correct type' raise exception.ClassNotFound(class_name=cls_name, exception=error_str) return classes
def replaceFunctionWithSourceString(namespace, functionName, allowEmpty=False): func = namespace.get(functionName) if not func: if allowEmpty: namespace[functionName] = '' return else: raise Exception('Function %s not found in input source code.' % functionName) if not inspect.isfunction(func): raise Exception('Object %s is not a function object.' % functionName) lines = inspect.getsourcelines(func)[0] if len(lines) <= 1: raise Exception('Function %s must not be a single line of code.' % functionName) # skip first line (the declaration) and then dedent the source code sourceCode = textwrap.dedent(''.join(lines[1:])) namespace[functionName] = sourceCode
def decorate_func_or_method_or_class(decorator): """Applies a decorator to a function, method, or all methods of a class. This is a decorator that is applied to a decorator to allow a function/method decorator to be applied to a class and have it act on all test methods of the class. """ def decorate(func_or_class): if inspect.isclass(func_or_class): return decorate_all_test_methods(decorator)(func_or_class) elif inspect.isfunction(func_or_class): return decorator(func_or_class) else: assert False, 'Target of decorator must be function or class' return decorate
def getargspec(func): """Variation of inspect.getargspec that works for more functions. This function works for Cythonized, non-cpdef functions, which expose argspec information but are not accepted by getargspec. It also works for Python 3 functions that use annotations, which are simply ignored. However, keyword-only arguments are not supported. """ if inspect.ismethod(func): func = func.__func__ # Cythonized functions have a .__code__, but don't pass inspect.isfunction() try: code = func.__code__ except AttributeError: raise TypeError('{!r} is not a Python function'.format(func)) if hasattr(code, 'co_kwonlyargcount') and code.co_kwonlyargcount > 0: raise ValueError('keyword-only arguments are not supported by getargspec()') args, varargs, varkw = inspect.getargs(code) return inspect.ArgSpec(args, varargs, varkw, func.__defaults__)
def __call__(self, func_or_cls): condition = self.condition reason = self.reason if inspect.isfunction(func_or_cls): @six.wraps(func_or_cls) def wrapped(*args, **kwargs): if condition: raise testtools.TestCase.skipException(reason) return func_or_cls(*args, **kwargs) return wrapped elif inspect.isclass(func_or_cls): orig_func = getattr(func_or_cls, 'setUp') @six.wraps(orig_func) def new_func(self, *args, **kwargs): if condition: raise testtools.TestCase.skipException(reason) orig_func(self, *args, **kwargs) func_or_cls.setUp = new_func return func_or_cls else: raise TypeError('skipUnless can be used only with functions or ' 'classes')
def _get_provider_submodule_method(module_name: str, submodule_name: str, method_name: str) -> Optional[Callable]: sub_module = "{}.{}".format(module_name, submodule_name) try: importlib.import_module(module_name, package='__path__') except ImportError: return None if importlib.util.find_spec(sub_module): site = importlib.import_module(sub_module, package=module_name) if hasattr(site, method_name): obj = getattr(site, method_name) if inspect.isfunction(obj): return obj return None # We should only create one ProviderContext over the program lifetime, # to avoid having to search the file system every time it's created. # This is why this should be outside Settings
def update_inputs(av_states, socket_send, *input_variable_names): # From each input variable name, extract the function name, ids of AvStates to be passed as arguments, # and the corresponding function from psaltlib.Inputs. Call the function with the id-key'd AvStates as # arguments. Aggregate results in order in a list. input_state = [] for term in input_variable_names: term_elements = re.split('_', term) function_name = term_elements[0] av_id_args = term_elements[1:] args = [] for av_id in av_id_args: args.append(av_states[int(av_id)]) args.append(socket_send) func = [o for o in getmembers(psaltlib.Inputs) if isfunction(o[1]) and o[0] == function_name] input_state.append(func[0][1](*args)) return input_state
def get_category(attr): if inspect.isclass(attr): return EXCEPTION if issubclass(attr, Exception) else CLASS elif inspect.isfunction(attr): return FUNCTION elif inspect.ismethod(attr): return FUNCTION elif inspect.isbuiltin(attr): return FUNCTION elif isinstance(attr, method_descriptor): # Technically, method_descriptor is descriptor, but since they # act as functions, let's treat them as functions. return FUNCTION elif is_descriptor(attr): # Maybe add getsetdescriptor memberdescriptor in the future. return DESCRIPTOR else: return DEFAULT_CATEGORY
def loadMacros(): path = os.path.abspath(os.path.dirname(__file__)) p = lambda x: os.path.splitext(x)[1] == ".py" modules = [x for x in os.listdir(path) if p(x) and not x == "__init__.py"] macros = {} for module in modules: name, _ = os.path.splitext(module) moduleName = "%s.%s" % (__package__, name) m = __import__(moduleName, globals(), locals(), __package__) p = lambda x: isfunction(x) and getmodule(x) is m for name, function in getmembers(m, p): name = name.replace("_", "-") try: macros[name] = function except Exception, e: continue return macros
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 command(*args, **kwargs): def set_command(func): if inspect.isfunction(func): if not hasattr(func, '_command'): func._command = [] for kw in kwargs: setattr(func, '_' + kw, kwargs.get(kw, False)) for arg in args: if arg not in func._command: func._command.append(arg) return func return set_command
def event(*args, **kwargs): def set_event(func): if inspect.isfunction(func): if not hasattr(func, '_event'): func._event = [] for kw in kwargs: setattr(func, '_' + kw, kwargs.get(kw, False)) for arg in args: if arg not in func._event: func._event.append(arg) return func return set_event
def __new__(cls, name, bases, attrs): # A list of all functions which is marked as 'is_cronjob=True' cron_jobs = [] # The min_tick is the greatest common divisor(GCD) of the interval of cronjobs # this value would be queried by scheduler when the project initial loaded. # Scheudler may only send _on_cronjob task every min_tick seconds. It can reduce # the number of tasks sent from scheduler. min_tick = 0 for each in attrs.values(): if inspect.isfunction(each) and getattr(each, 'is_cronjob', False): cron_jobs.append(each) min_tick = fractions.gcd(min_tick, each.tick) newcls = type.__new__(cls, name, bases, attrs) newcls._cron_jobs = cron_jobs newcls._min_tick = min_tick return newcls
def test_stacking_instead(decor): """Test stacking when instead is specified last (which is WRONG) Note that putting instead late in the stack WILL override any previous decorators! """ tracker = Mock(name='tracker', return_value=None) decorated = Mock(name='decorated', return_value='decorated') tracker.__name__ = str('tracker') decorated.__name__ = str('decorated') fn = decor(tracker)(decorated) fn = instead(tracker)(fn) fn() decorated.assert_not_called() assert tracker.call_count == 1 assert tracker.call_args[0][:2] == ((), {}) assert isfunction(tracker.call_args[0][2])
def test_parse_identifiers(): """pyessv-tests: parsing: identifiers """ def positive_test(parser, project, identifier): parser(project, identifier) @nose.tools.raises(LIB.TemplateParsingError) def negative_test(parser, project, identifier): parser(project, identifier) # Iterate identifiers & perform +ve / -ve tests: for project, parser, seperator, identifiers in _CONFIG: assert inspect.isfunction(parser) for identifier in identifiers: # ... +ve test: desc = 'identifier parsing test (+ve) --> {} :: {}'.format(project, identifier) tu.init(positive_test, desc) yield positive_test, parser, project, identifier # ... -ve tests: for invalid_identifier in _get_invalid_identifiers(identifier, seperator): desc = 'identifier parsing test (-ve) --> {} :: {}'.format(project, invalid_identifier) tu.init(negative_test, desc) yield negative_test, parser, project, invalid_identifier
def __new__(cls, name, bases, attrs): super_new = super(AccountActionMetaclass, cls).__new__ parents = [base for base in bases if isinstance(base, AccountActionMetaclass)] if not parents: # We stop here if we are considering AccountActionBase and not # one of its subclasses return super_new(cls, name, bases, attrs) new_action = super_new(cls, name, bases, attrs) # Performs some checks action_name = getattr(new_action, 'name', None) if action_name is None or not isinstance(action_name, six.string_types): raise ImproperlyConfigured('The "name" attribute must be a string') execute_method = getattr(new_action, 'execute', None) if execute_method is None or \ not (inspect.ismethod(execute_method) or inspect.isfunction(execute_method)): raise ImproperlyConfigured('The "execute" method must be configured') return new_action
def extract_data_from_funcs(node_funcs): print("node_funcs is:", node_funcs) if isinstance(node_funcs, list): node_data = [] for func in node_funcs: if inspect.isfunction(func): node_data.append(func()) else: node_data.append(func) return node_data elif inspect.isfunction(node_funcs): return node_funcs() else: return node_funcs # Tells the dimensionality of the data (independent of number of samples or number of data arrays)
def append_dataset_arrays_or_functions(dataset1, dataset2, verbose=True): """Concatenates the features of two ndarrays (or functions returning ndarrays).""" if inspect.isfunction(dataset1): if verbose: print("Executing dataset1") d1 = dataset1() else: if verbose: print("Dataset1 is an array") d1 = dataset1 if inspect.isfunction(dataset2): if verbose: print("Executing dataset2") d2 = dataset2() else: if verbose: print("Dataset2 is an array") d2 = dataset2 n1 = d1.shape[0] n2 = d2.shape[0] if n1 != n2: er = "incompatible number of samples: ", n1, " and ", n2 raise Exception(er) return numpy.concatenate((d1, d2), axis=1)