Python inspect.isfunction() Examples

The following are 30 code examples of inspect.isfunction(). 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: decorators.py    From eventsourcing with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def applicationpolicy(arg: Callable) -> Callable:
    """
    Decorator for application policy method.

    Allows policy to be built up from methods
    registered for different event classes.
    """

    assert isfunction(arg), arg

    @no_type_check
    def _mutator(func):
        wrapped = singledispatch(func)

        @wraps(wrapped)
        def wrapper(*args, **kwargs):
            event = kwargs.get("event") or args[-1]
            return wrapped.dispatch(type(event))(*args, **kwargs)

        wrapper.register = wrapped.register

        return wrapper

    return _mutator(arg) 
Example #2
Source File: langhelpers.py    From jbox with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: base_handler.py    From pyspider with Apache License 2.0 6 votes vote down vote up
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 
Example #4
Source File: decorators.py    From eventsourcing with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def attribute(getter: Callable) -> property:
    """
    When used as a method decorator, returns a property object
    with the method as the getter and a setter defined to call
    instance method __change_attribute__(), which publishes an
    AttributeChanged event.
    """
    if isfunction(getter):

        @no_type_check
        def setter(self, value):
            name = "_" + getter.__name__
            self.__change_attribute__(name=name, value=value)

        @no_type_check
        def new_getter(self):
            name = "_" + getter.__name__
            return getattr(self, name, None)

        return property(fget=new_getter, fset=setter, doc=getter.__doc__)
    else:
        raise ProgrammingError("Expected a function, got: {}".format(repr(getter))) 
Example #5
Source File: pycodestyle.py    From linter-pylama with MIT License 6 votes vote down vote up
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)
    return check


##############################################################################
# Plugins (check functions) for physical lines
############################################################################## 
Example #6
Source File: loadables.py    From zun with Apache License 2.0 6 votes vote down vote up
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 
Example #7
Source File: __init__.py    From pyta with GNU General Public License v3.0 6 votes vote down vote up
def check_all_contracts(*args, decorate_main=True) -> None:
    """Automatically check contracts for all functions and classes in the given module.

    When called with no arguments, the current module's functions and classes are checked.
    """

    modules = []
    if decorate_main:
        modules.append(sys.modules["__main__"])

    for module_name in args:
        modules.append(sys.modules.get(module_name, None))

    for module in modules:
        if not module:
            # Module name was passed in incorrectly.
            continue
        for name, value in inspect.getmembers(module):
            if inspect.isfunction(value):
                module.__dict__[name] = check_contracts(value)
            elif inspect.isclass(value):
                add_class_invariants(value) 
Example #8
Source File: doctest24.py    From mishkal with GNU General Public License v3.0 6 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.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") 
Example #9
Source File: base.py    From terraform-templates with Apache License 2.0 6 votes vote down vote up
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 #10
Source File: validator.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def validate(self, value, data):
        if self.condition is None and not self._is_empty(value):
            need_validate = True
        else:
            assert isfunction(self.condition), \
                'Condition should be a function for RequiresIf validator'
            need_validate = self.condition(value, data)
        if not need_validate:
            return True

        fields = []
        for field in self.fields:
            val = data.get(field)
            if val is None or val == '':
                fields.append(field)
        if fields:
            self.put_msg(
                'For given input, fields are required: %s' % ', '.join(fields)
            )
            return False
        return True 
Example #11
Source File: transcoding.py    From eventsourcing with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def encoderpolicy(arg=None):
    """
    Decorator for encoder policy.

    Allows default behaviour to be built up from methods
    registered for different types of things, rather than
    chain of isinstance() calls in a long if-else block.
    """

    def _mutator(func):
        wrapped = singledispatch(func)

        @wraps(wrapped)
        def wrapper(*args, **kwargs):
            obj = kwargs.get("obj") or args[-1]
            return wrapped.dispatch(type(obj))(*args, **kwargs)

        wrapper.register = wrapped.register

        return wrapper

    assert isfunction(arg), arg
    return _mutator(arg) 
Example #12
Source File: transcoding_v1.py    From eventsourcing with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def encoderpolicy(arg=None):
    """
    Decorator for encoder policy.

    Allows default behaviour to be built up from methods
    registered for different types of things, rather than
    chain of isinstance() calls in a long if-else block.
    """

    def _mutator(func):
        wrapped = singledispatch(func)

        @wraps(wrapped)
        def wrapper(*args, **kwargs):
            obj = kwargs.get("obj") or args[-1]
            return wrapped.dispatch(type(obj))(*args, **kwargs)

        wrapper.register = wrapped.register

        return wrapper

    assert isfunction(arg), arg
    return _mutator(arg) 
Example #13
Source File: util.py    From browserscope with Apache License 2.0 6 votes vote down vote up
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 #14
Source File: util.py    From browserscope with Apache License 2.0 6 votes vote down vote up
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: util.py    From browserscope with Apache License 2.0 6 votes vote down vote up
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 #16
Source File: magic_check_fn.py    From recipes-py with Apache License 2.0 6 votes vote down vote up
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 #17
Source File: validator.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def validate(self, value, data):
        if self.condition is None and not self._is_empty(value):
            need_validate = True
        else:
            assert isfunction(self.condition), \
                'Condition should be a function for RequiresIf validator'
            need_validate = self.condition(value, data)
        if not need_validate:
            return True

        fields = []
        for field in self.fields:
            val = data.get(field)
            if val is None or val == '':
                fields.append(field)
        if fields:
            self.put_msg(
                'For given input, fields are required: %s' % ', '.join(fields)
            )
            return False
        return True 
Example #18
Source File: check_api.py    From git-pandas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def extract_objects(m, classes=True, functions=False):
    # add in the classes at this level
    out = {}
    if classes:
        m_dict = {k: v for k, v in m.__dict__.items() if inspect.isclass(v)}
        out.update(m_dict)
    if functions:
        m_dict = {k: v for k, v in m.__dict__.items() if inspect.isfunction(v)}
        out.update(m_dict)

    return out 
Example #19
Source File: noseclasses.py    From recruit with Apache License 2.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.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.
        else:
            raise ValueError("object must be a class or function") 
Example #20
Source File: common.py    From ec2-api with Apache License 2.0 5 votes vote down vote up
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 #21
Source File: pytestplugin.py    From jbox with MIT License 5 votes vote down vote up
def pytest_pycollect_makeitem(collector, name, obj):
    if inspect.isclass(obj) and plugin_base.want_class(obj):
        return pytest.Class(name, parent=collector)
    elif inspect.isfunction(obj) and \
            isinstance(collector, pytest.Instance) and \
            plugin_base.want_method(collector.cls, obj):
        return pytest.Function(name, parent=collector)
    else:
        return [] 
Example #22
Source File: test_docstrings.py    From collectd-haproxy with MIT License 5 votes vote down vote up
def get_module_functions(module):
    for name, func in inspect.getmembers(module, predicate=inspect.isfunction):
        yield (name, func) 
Example #23
Source File: configuration.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def get(key: str) -> Optional[Union[str, List[str], int, float]]:
    if key in CONFIG:
        return CONFIG[key]
    subkey = RE_SUBKEY.match(key)
    if subkey:
        return get_sub(subkey)
    try:
        cfg = json.load(open('config.json'))
    except FileNotFoundError:
        cfg = {}
    if key in os.environ:
        cfg[key] = os.environ[key]
        print('CONFIG: {0}={1}'.format(key, cfg[key]))
        return cfg[key]
    if key in cfg:
        CONFIG.update(cfg)
        return cfg[key]
    if key in DEFAULTS:
        # Lock in the default value if we use it.
        cfg[key] = DEFAULTS[key]

        if inspect.isfunction(cfg[key]): # If default value is a function, call it.
            cfg[key] = cfg[key]()
    else:
        raise InvalidArgumentException('No default or other configuration value available for {key}'.format(key=key))

    print('CONFIG: {0}={1}'.format(key, cfg[key]))
    fh = open('config.json', 'w')
    fh.write(json.dumps(cfg, indent=4, sort_keys=True))
    return cfg[key] 
Example #24
Source File: modules.py    From Nest with MIT License 5 votes vote down vote up
def _register(*args, **kwargs) -> Callable:
        """Decorator for Nest modules registration.

        Parameters:
            ignored:
                Ignore the module

            module meta information which could be utilized by CLI and UI. For example:
            author: 
                Module author(s), e.g., 'Zhou, Yanzhao'
            version: 
                Module version, e.g., '1.2.0'
            backend:
                Module backend, e.g., 'pytorch'
            tags: 
                Searchable tags, e.g., ['loss', 'cuda_only']
            etc.
        """

        # ignore the Nest module (could be used for debuging)
        if kwargs.pop('ignored', False):
            return lambda x: x

        # use the rest of kwargs to update metadata
        frame = inspect.stack()[1]
        current_py_module = inspect.getmodule(frame[0])
        nest_meta = U.merge_dict(getattr(current_py_module, '__nest_meta__', dict()), kwargs, union=True)
        if current_py_module is not None:
            setattr(current_py_module, '__nest_meta__', nest_meta)

        def create_module(func):
            # append meta to doc
            doc = (func.__doc__ + '\n' + (U.yaml_format(nest_meta) if len(nest_meta) > 0 else '')) \
                if isinstance(func.__doc__, str) else None
            return type('NestModule', (NestModule,), dict(__slots__=(), __doc__=doc))(func, nest_meta)

        if len(args) == 1 and inspect.isfunction(args[0]):
            return create_module(args[0])
        else:
            return create_module 
Example #25
Source File: test_docstring_parameters.py    From celer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_documented():
    """Test that public functions and classes are documented."""
    public_modules_ = public_modules[:]

    doc_file = op.abspath(op.join(op.dirname(__file__), '..', '..', 'doc',
                                  'api.rst'))
    if not op.isfile(doc_file):
        raise SkipTest('Documentation file not found: %s' % doc_file)
    known_names = list()
    with open(doc_file, 'rb') as fid:
        for line in fid:
            line = line.decode('utf-8')
            if not line.startswith('  '):  # at least two spaces
                continue
            line = line.split()
            if len(line) == 1 and line[0] != ':':
                known_names.append(line[0].split('.')[-1])
    known_names = set(known_names)

    missing = []
    for name in public_modules_:
        with warnings.catch_warnings(record=True):  # traits warnings
            module = __import__(name, globals())
        for submod in name.split('.')[1:]:
            module = getattr(module, submod)
        classes = inspect.getmembers(module, inspect.isclass)
        functions = inspect.getmembers(module, inspect.isfunction)
        checks = list(classes) + list(functions)
        for name, cf in checks:
            if not name.startswith('_') and name not in known_names:
                from_mod = inspect.getmodule(cf).__name__
                if (from_mod.startswith('celer') and
                        from_mod not in documented_ignored_mods and
                        name not in documented_ignored_names):
                    missing.append('%s (%s.%s)' % (name, from_mod, name))
    if len(missing) > 0:
        raise AssertionError('\n\nFound new public members missing from '
                             'doc/python_reference.rst:\n\n* ' +
                             '\n* '.join(sorted(set(missing)))) 
Example #26
Source File: base.py    From transformpy with MIT License 5 votes vote down vote up
def init(self, outputter, *args, **kwargs):
        self.is_function = inspect.isfunction(outputter)
        if not self.is_function:
            if inspect.isclass(outputter):
                outputter = outputter(*args, **kwargs)
            assert outputter.type == TransformType.SINK
        self.__outputter = outputter 
Example #27
Source File: test_readlinecommands.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def test_none(qtbot):
    """Call each rl_* method with a None focusWidget."""
    assert QApplication.instance().focusWidget() is None
    for name, method in inspect.getmembers(readlinecommands,
                                           inspect.isfunction):
        if name.startswith('rl_'):
            method() 
Example #28
Source File: starlette_plugin.py    From spectree with Apache License 2.0 5 votes vote down vote up
def find_routes(self):
        routes = []

        def parse_route(app, prefix=''):
            for route in app.routes:
                if route.path.startswith(f'/{self.config.PATH}'):
                    continue

                func = route.app
                if isinstance(func, partial):
                    try:
                        func = func.__wrapped__
                    except AttributeError:
                        pass

                if inspect.isclass(func):
                    for method in METHODS:
                        if getattr(func, method, None):
                            routes.append(Route(
                                f'{prefix}{route.path}',
                                {method.upper()},
                                getattr(func, method)
                            ))
                elif inspect.isfunction(func):
                    routes.append(Route(
                        f'{prefix}{route.path}',
                        route.methods,
                        route.endpoint))
                else:
                    parse_route(route, prefix=f'{prefix}{route.path}')

        parse_route(self.app)
        return routes 
Example #29
Source File: bootstrap.py    From loaner with Apache License 2.0 5 votes vote down vote up
def get_bootstrap_functions(get_all=False):
  """Gets all functions necessary for bootstrap.

  This function collects only the functions necessary for the bootstrap
  process. Specifically, it will collect tasks specific to a new or existing
  deployment (an update). Additionally, it will collect any failed tasks so that
  they can be attempted again.

  Args:
    get_all: bool, return all bootstrap tasks, defaults to False.

  Returns:
    Dict, all functions necessary for bootstrap.
  """
  module_functions = inspect.getmembers(
      sys.modules[__name__], inspect.isfunction)
  bootstrap_functions = {
      key: value
      for key, value in dict(module_functions)
      .iteritems() if key.startswith('bootstrap_')
  }

  if get_all or _is_new_deployment():
    return bootstrap_functions

  if is_update():
    bootstrap_functions = {
        key: value for key, value in bootstrap_functions.iteritems()
        if key in _BOOTSTRAP_UPDATE_TASKS
    }
  else:  # Collect all bootstrap functions that failed and all update tasks.
    for function_name in bootstrap_functions.keys():
      status_entity = bootstrap_status_model.BootstrapStatus.get_by_id(
          function_name)
      if (status_entity and
          status_entity.success and
          function_name not in _BOOTSTRAP_UPDATE_TASKS):
        del bootstrap_functions[function_name]
  return bootstrap_functions 
Example #30
Source File: pytestplugin.py    From jbox with MIT License 5 votes vote down vote up
def pytest_pycollect_makeitem(collector, name, obj):
    if inspect.isclass(obj) and plugin_base.want_class(obj):
        return pytest.Class(name, parent=collector)
    elif inspect.isfunction(obj) and \
            isinstance(collector, pytest.Instance) and \
            plugin_base.want_method(collector.cls, obj):
        return pytest.Function(name, parent=collector)
    else:
        return []