Python inspect.ismethod() Examples
The following are 30
code examples of inspect.ismethod().
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: terms.py From pypika with Apache License 2.0 | 7 votes |
def __getattr__(self, name: str) -> Any: """ Delegate method calls to the class wrapped by Not(). Re-wrap methods on child classes of Term (e.g. isin, eg...) to retain 'NOT <term>' output. """ item_func = getattr(self.term, name) if not inspect.ismethod(item_func): return item_func def inner(inner_self, *args, **kwargs): result = item_func(inner_self, *args, **kwargs) if isinstance(result, (Term,)): return Not(result) return result return inner
Example #2
Source File: model_checks.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def check_all_models(app_configs=None, **kwargs): errors = [] for model in apps.get_models(): if app_configs is None or model._meta.app_config in app_configs: if not inspect.ismethod(model.check): errors.append( Error( "The '%s.check()' class method is " "currently overridden by %r." % ( model.__name__, model.check), hint=None, obj=model, id='models.E020' ) ) else: errors.extend(model.check(**kwargs)) return errors
Example #3
Source File: asyn.py From filesystem_spec with BSD 3-Clause "New" or "Revised" License | 6 votes |
def mirror_sync_methods(obj): """Populate sync and async methods for obj For each method will create a sync version if the name refers to an async method (coroutine) and there is no override in the child class; will create an async method for the corresponding sync method if there is no implementation. Uses the methods specified in - async_methods: the set that an implementation is expected to provide - default_async_methods: that can be derived from their sync version in AbstractFileSystem - AsyncFileSystem: async-specific default implementations """ from fsspec import AbstractFileSystem for method in async_methods + default_async_methods + dir(AsyncFileSystem): smethod = method[1:] if private.match(method): if inspect.iscoroutinefunction(getattr(obj, method, None)) and getattr( obj, smethod, False ).__func__ is getattr(AbstractFileSystem, smethod): setattr(obj, smethod, sync_wrapper(getattr(obj, method), obj=obj)) elif hasattr(obj, smethod) and inspect.ismethod(getattr(obj, smethod)): setattr(obj, method, async_wrapper(getattr(obj, smethod)))
Example #4
Source File: document.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def collect_options(mcs, bases, attrs): """ Collects options from the current class and its parent classes. :returns: a dictionary of options """ options = {} # options from parent classes: for base in reversed(bases): if hasattr(base, '_options'): for key, value in inspect.getmembers(base._options): if not key.startswith('_') and value is not None: options[key] = value # options from the current class: if 'Options' in attrs: for key, value in inspect.getmembers(attrs['Options']): if not key.startswith('_') and value is not None: # HACK HACK HACK if inspect.ismethod(value) and value.im_self is None: value = value.im_func options[key] = value return options
Example #5
Source File: WidgetGroup.py From tf-pose with Apache License 2.0 | 6 votes |
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
Example #6
Source File: WidgetGroup.py From tf-pose with Apache License 2.0 | 6 votes |
def readWidget(self, w): if type(w) in WidgetGroup.classes: getFunc = WidgetGroup.classes[type(w)][1] else: getFunc = w.widgetGroupInterface()[1] if getFunc is None: return None ## if the getter function provided in the interface is a bound method, ## then just call the method directly. Otherwise, pass in the widget as the first arg ## to the function. if inspect.ismethod(getFunc) and getFunc.__self__ is not None: val = getFunc() else: val = getFunc(w) if self.scales[w] is not None: val /= self.scales[w] #if isinstance(val, QtCore.QString): #val = str(val) n = self.widgetList[w] self.cache[n] = val return val
Example #7
Source File: WidgetGroup.py From tf-pose with Apache License 2.0 | 6 votes |
def setWidget(self, w, v): v1 = v if self.scales[w] is not None: v *= self.scales[w] if type(w) in WidgetGroup.classes: setFunc = WidgetGroup.classes[type(w)][2] else: setFunc = w.widgetGroupInterface()[2] ## if the setter function provided in the interface is a bound method, ## then just call the method directly. Otherwise, pass in the widget as the first arg ## to the function. if inspect.ismethod(setFunc) and setFunc.__self__ is not None: setFunc(v) else: setFunc(w, v) #name = self.widgetList[w] #if name in self.cache and (self.cache[name] != v1): #print "%s: Cached value %s != set value %s" % (name, str(self.cache[name]), str(v1))
Example #8
Source File: magic_check_fn.py From recipes-py with Apache License 2.0 | 6 votes |
def _get_name_of_callable(cls, c): if inspect.ismethod(c): return c.im_class.__name__+'.'+c.__name__ if inspect.isfunction(c): if c.__name__ == (lambda: None).__name__: filename = c.func_code.co_filename cls._ensure_file_in_cache(filename, c) definitions = cls._LAMBDA_CACHE[filename][c.func_code.co_firstlineno] assert definitions # If there's multiple definitions at the same line, there's not enough # information to distinguish which lambda c refers to, so just let # python's generic lambda name be used if len(definitions) == 1: return astunparse.unparse(definitions[0]).strip() return c.__name__ if hasattr(c, '__call__'): return c.__class__.__name__+'.__call__' return repr(c)
Example #9
Source File: base_action.py From loaner with Apache License 2.0 | 6 votes |
def __init__(self): """Validates required attributes for Action subclasses.""" if not isinstance(getattr(self, 'ACTION_NAME', None), basestring): raise AttributeError(_NO_ACTION_NAME_MSG % self.__class__.__name__) if not isinstance(getattr(self, 'FRIENDLY_NAME', None), basestring): raise AttributeError(_NO_FRIENDLY_NAME_MSG % self.__class__.__name__) try: if not inspect.ismethod(super(BaseAction, self).__getattribute__('run')): raise AttributeError() except AttributeError: raise AttributeError(_NO_RUN_METHOD_MSG % self.__class__.__name__) self.action_type = getattr(self, 'ACTION_TYPE', ActionType.ASYNC) if self.action_type not in (ActionType.SYNC, ActionType.ASYNC): raise AttributeError( _BAD_ACTION_TYPE_MSG % (self.__class__.__name__, str(self.action_type)))
Example #10
Source File: full.py From tekore with MIT License | 6 votes |
def test_all_endpoints_have_scope_attributes(self, client): # Skip paging calls and options skips = { 'next', 'previous', 'all_pages', 'all_items', 'chunked', 'max_limits', 'token_as', } for name, method in getmembers(client, predicate=ismethod): if name.startswith('_') or name in skips: continue assert isinstance(method.scope, Scope) assert isinstance(method.required_scope, Scope) assert isinstance(method.optional_scope, Scope) assert method.scope == method.required_scope + method.optional_scope
Example #11
Source File: manager.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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
Example #12
Source File: python.py From python-netsurv with MIT License | 6 votes |
def _get_xunit_setup_teardown(holder, attr_name, param_obj=None): """ Return a callable to perform xunit-style setup or teardown if the function exists in the ``holder`` object. The ``param_obj`` parameter is the parameter which will be passed to the function when the callable is called without arguments, defaults to the ``holder`` object. Return ``None`` if a suitable callable is not found. """ # TODO: only needed because of Package! param_obj = param_obj if param_obj is not None else holder result = _get_non_fixture_func(holder, attr_name) if result is not None: arg_count = result.__code__.co_argcount if inspect.ismethod(result): arg_count -= 1 if arg_count: return lambda: result(param_obj) else: return result
Example #13
Source File: util.py From browserscope with Apache License 2.0 | 6 votes |
def is_generator_function(obj): """Return true if the object is a user-defined generator function. Generator function objects provides same attributes as functions. See isfunction.__doc__ for attributes listing. Adapted from Python 2.6. Args: obj: an object to test. Returns: true if the object is generator function. """ CO_GENERATOR = 0x20 return bool(((inspect.isfunction(obj) or inspect.ismethod(obj)) and obj.func_code.co_flags & CO_GENERATOR))
Example #14
Source File: util.py From browserscope with Apache License 2.0 | 6 votes |
def is_generator(obj): """Return true if the object is generator or generator function. Generator function objects provides same attributes as functions. See isfunction.__doc__ for attributes listing. Adapted from Python 2.6. Args: obj: an object to test. Returns: true if the object is generator function. """ if isinstance(obj, types.GeneratorType): return True CO_GENERATOR = 0x20 return bool(((inspect.isfunction(obj) or inspect.ismethod(obj)) and obj.func_code.co_flags & CO_GENERATOR))
Example #15
Source File: python.py From python-netsurv with MIT License | 6 votes |
def _get_xunit_setup_teardown(holder, attr_name, param_obj=None): """ Return a callable to perform xunit-style setup or teardown if the function exists in the ``holder`` object. The ``param_obj`` parameter is the parameter which will be passed to the function when the callable is called without arguments, defaults to the ``holder`` object. Return ``None`` if a suitable callable is not found. """ # TODO: only needed because of Package! param_obj = param_obj if param_obj is not None else holder result = _get_non_fixture_func(holder, attr_name) if result is not None: arg_count = result.__code__.co_argcount if inspect.ismethod(result): arg_count -= 1 if arg_count: return lambda: result(param_obj) else: return result
Example #16
Source File: wuy.py From wuy with GNU General Public License v2.0 | 6 votes |
def __init__(self, log=True): global isLog isLog = log self._name = self.__class__.__name__ self._routes = { n: v for n, v in inspect.getmembers(self, inspect.ismethod) if not v.__func__.__qualname__.startswith(("Base.", "Window.", "Server.")) } self._routes.update( dict(set=self.set, get=self.get) ) # add get/set config methods if "init" in self._routes: del self._routes[ "init" ] # ensure that a server-side init() is not exposed on client-side self._clients = []
Example #17
Source File: base.py From terraform-templates with Apache License 2.0 | 6 votes |
def __init__(self, *args, **kwargs): self.pan_device = kwargs.pop('pan_device', None) pan.xapi.PanXapi.__init__(self, *args, **kwargs) pred = lambda x: inspect.ismethod(x) or inspect.isfunction(x) # inspect.ismethod needed for Python2, inspect.isfunction needed for Python3 for name, method in inspect.getmembers( pan.xapi.PanXapi, pred): # Ignore hidden methods if name[0] == "_": continue # Ignore non-api methods if name in ('xml_result', 'xml_root', 'cmd_xml'): continue # Wrapper method. This is used to create # methods in this class that match the methods in the # super class, and call the super class methods inside # a try/except block, which allows us to check and # analyze the exceptions and convert them to more # useful exceptions than generic PanXapiErrors. wrapper_method = PanDevice.XapiWrapper.make_method(name, method) # Create method matching each public method of the base class setattr(PanDevice.XapiWrapper, name, wrapper_method)
Example #18
Source File: util.py From browserscope with Apache License 2.0 | 6 votes |
def try_serialize_handler(handler): """Try to serialize map/reduce handler. Args: handler: handler function/instance. Handler can be a function or an instance of a callable class. In the latter case, the handler will be serialized across slices to allow users to save states. Returns: serialized handler string or None. """ if (isinstance(handler, types.InstanceType) or # old style class (isinstance(handler, object) and # new style class not inspect.isfunction(handler) and not inspect.ismethod(handler)) and hasattr(handler, "__call__")): return pickle.dumps(handler) return None
Example #19
Source File: converter.py From discord.py with MIT License | 6 votes |
def convert(self, ctx, argument): arg = argument.replace('0x', '').lower() if arg[0] == '#': arg = arg[1:] try: value = int(arg, base=16) if not (0 <= value <= 0xFFFFFF): raise BadArgument('Colour "{}" is invalid.'.format(arg)) return discord.Colour(value=value) except ValueError: arg = arg.replace(' ', '_') method = getattr(discord.Colour, arg, None) if arg.startswith('from_') or method is None or not inspect.ismethod(method): raise BadArgument('Colour "{}" is invalid.'.format(arg)) return method()
Example #20
Source File: autopep8.py From python-netsurv with MIT License | 5 votes |
def _get_parameters(function): # pylint: disable=deprecated-method if sys.version_info.major >= 3: # We need to match "getargspec()", which includes "self" as the first # value for methods. # https://bugs.python.org/issue17481#msg209469 if inspect.ismethod(function): function = function.__func__ return list(inspect.signature(function).parameters) else: return inspect.getargspec(function)[0]
Example #21
Source File: cli.py From cli with MIT License | 5 votes |
def do_help(self, arg): methods = inspect.getmembers(CodeShell, predicate=inspect.ismethod) for key, method in methods: if key.startswith('do_'): name = key.split('_')[1] doc = method.__doc__ if (not arg or arg == name) and doc: print name, '\t', doc print """ A tag can refer to a topic (e.g. array) or a company (e.g. amazon). A keyword can be anything (including a tag). Commands and options can be completed by <TAB>."""
Example #22
Source File: ke4_model_source.py From kylinpy with MIT License | 5 votes |
def invoke_command(self, command, **kwargs): fn = getattr(self, str(command), None) if ( fn is None or not inspect.ismethod(fn) or fn.__name__ not in self.support_invoke_command ): raise KylinModelError('Unsupported invoke command for datasource: {}'.format(command)) eager_args = [arg for arg in inspect.getargspec(fn).args if arg != 'self'] args = {key: kwargs[key] for key in kwargs.keys() if key in eager_args} return fn(**args)
Example #23
Source File: python.py From python-netsurv with MIT License | 5 votes |
def _call_with_optional_argument(func, arg): """Call the given function with the given argument if func accepts one argument, otherwise calls func without arguments""" arg_count = func.__code__.co_argcount if inspect.ismethod(func): arg_count -= 1 if arg_count: func(arg) else: func()
Example #24
Source File: autopep8.py From python-netsurv with MIT License | 5 votes |
def _get_parameters(function): # pylint: disable=deprecated-method if sys.version_info.major >= 3: # We need to match "getargspec()", which includes "self" as the first # value for methods. # https://bugs.python.org/issue17481#msg209469 if inspect.ismethod(function): function = function.__func__ return list(inspect.signature(function).parameters) else: return inspect.getargspec(function)[0]
Example #25
Source File: python.py From python-netsurv with MIT License | 5 votes |
def _call_with_optional_argument(func, arg): """Call the given function with the given argument if func accepts one argument, otherwise calls func without arguments""" arg_count = func.__code__.co_argcount if inspect.ismethod(func): arg_count -= 1 if arg_count: func(arg) else: func()
Example #26
Source File: langhelpers.py From jbox with MIT License | 5 votes |
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 #27
Source File: common.py From typhon with MIT License | 5 votes |
def read(self, filename, **kwargs): """Open a file by its name, read its content and return it Notes: This is the base class method that does nothing per default. Args: filename: A string containing path and name or a :class:`FileInfo` object of the file from which to read. **kwargs: Additional key word arguments. Returns: An object containing the file's content (e.g. numpy array, etc.). """ if self.reader is not None: # Some functions do not accept additional key word arguments (via # kwargs). And if they are methods, they accept an additional # "self" or "class" parameter. number_args = 1 + int(ismethod(self.reader)) if len(signature(self.reader).parameters) > number_args: return self.reader(filename, **kwargs) else: return self.reader(filename) raise NotImplementedError( "This file handler does not support reading data from a file. You " "should use a different file handler.")
Example #28
Source File: common.py From typhon with MIT License | 5 votes |
def get_info(self, filename, **kwargs): """Return a :class:`FileInfo` object with parameters about the file content. Notes: This is the base class method that does nothing per default. Args: filename: A string containing path and name or a :class:`FileInfo` object of the file of which to get the information about. **kwargs: Additional keyword arguments. Returns: A :class:`FileInfo` object. """ if self.info is not None: # Some functions do not accept additional key word arguments (via # kwargs). And if they are methods, they accept an additional # "self" or "class" parameter. number_args = 1 + int(ismethod(self.info)) if len(signature(self.info).parameters) > number_args: return self.info(filename, **kwargs) else: return self.info(filename) raise NotImplementedError( "This file handler does not support reading data from a file. You " "should use a different file handler.")
Example #29
Source File: common.py From ec2-api with Apache License 2.0 | 5 votes |
def _run_cleanups(self, cleanups): for function, args, kwargs in reversed(cleanups): try: function(*args, **kwargs) except Exception: if inspect.ismethod(function): if six.PY2: cmodule = function.im_class.__module__ cname = function.im_class.__name__ else: cmodule = function.__self__.__class__.__module__ cname = function.__self__.__class__.__name__ name = '%s.%s.%s' % (cmodule, cname, function.__name__) elif inspect.isfunction(function): name = '%s.%s' % (function.__module__, function.__name__) else: name = '%s.%s' % (function.__class__.__module__, function.__class__.__name__) formatted_args = '' args_string = ', '.join([repr(arg) for arg in args]) kwargs_string = ', '.join([ '%s=%r' % (key, value) for key, value in kwargs.items() ]) if args_string: formatted_args = args_string if kwargs_string: if formatted_args: formatted_args += ', ' formatted_args += kwargs_string LOG.warning( 'Error cleaning up %(name)s(%(args)s)' % {'name': name, 'args': formatted_args}, exc_info=True) pass
Example #30
Source File: mox.py From browserscope with Apache License 2.0 | 5 votes |
def __init__(self, method): """Creates a checker. Args: # method: A method to check. method: function Raises: ValueError: method could not be inspected, so checks aren't possible. Some methods and functions like built-ins can't be inspected. """ try: self._args, varargs, varkw, defaults = inspect.getargspec(method) except TypeError: raise ValueError('Could not get argument specification for %r' % (method,)) if inspect.ismethod(method): self._args = self._args[1:] # Skip 'self'. self._method = method self._has_varargs = varargs is not None self._has_varkw = varkw is not None if defaults is None: self._required_args = self._args self._default_args = [] else: self._required_args = self._args[:-len(defaults)] self._default_args = self._args[-len(defaults):]