Python inspect.isroutine() Examples

The following are 30 code examples of inspect.isroutine(). 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: jobs.py    From pypette with MIT License 6 votes vote down vote up
def __init__(self, function, args=(), kwargs={}):
        """Constructor.

        :param function: Python method to run.
        :type function: routine
        :param args: Argument list to run the method with.
        :type args: tuple
        :param kwargs: Keyword arguments to run the method with.
        :type kwargs: dict
        """
        assert isroutine(function), "Python callable expected"
        assert isinstance(args, tuple)
        assert isinstance(kwargs, dict)

        super(Job, self).__init__(function.__name__)
        self.function = function
        self.args = args
        self.kwargs = kwargs 
Example #2
Source File: event.py    From flappy-bird-py with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #3
Source File: pydoc.py    From jawfish with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: pydoc.py    From jawfish with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: event.py    From flappy-bird-py with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #6
Source File: base.py    From testplan with Apache License 2.0 6 votes vote down vote up
def denormalize(self):
        """
        Create new config object that inherits all explicit attributes from
        its parents as well.
        """
        new_options = {}
        for key in self._options:
            value = getattr(self, key)
            if inspect.isclass(value) or inspect.isroutine(value):
                # Skipping non-serializable classes and routines.
                logger.TESTPLAN_LOGGER.debug(
                    "Skip denormalizing option: %s", key
                )
                continue
            try:
                new_options[copy.deepcopy(key)] = copy.deepcopy(value)
            except Exception as exc:
                logger.TESTPLAN_LOGGER.warning(
                    "Failed to denormalize option: {} - {}".format(key, exc)
                )

        new = self.__class__(**new_options)
        return new 
Example #7
Source File: test_client.py    From spectacles with MIT License 6 votes vote down vote up
def get_client_method_names() -> List[str]:
    """Extracts method names from LookerClient to test for bad responses"""
    client_members: List[Tuple[str, Callable]] = inspect.getmembers(
        LookerClient, predicate=inspect.isroutine
    )
    client_methods: List[str] = [
        member[0] for member in client_members if not member[0].startswith("__")
    ]
    for skip_method in (
        "authenticate",
        "cancel_query_task",
        "request",
        "get",
        "post",
        "put",
        "patch",
        "delete",
    ):
        client_methods.remove(skip_method)
    return client_methods 
Example #8
Source File: manager.py    From python-netsurv with MIT License 6 votes vote down vote up
def parse_hookimpl_opts(self, plugin, name):
        method = getattr(plugin, name)
        if not inspect.isroutine(method):
            return
        try:
            res = getattr(method, self.project_name + "_impl", None)
        except Exception:
            res = {}
        if res is not None and not isinstance(res, dict):
            # false positive
            res = None
        # TODO: remove when we drop implprefix in 1.0
        elif res is None and self._implprefix and name.startswith(self._implprefix):
            _warn_for_function(
                DeprecationWarning(
                    "The `implprefix` system is deprecated please decorate "
                    "this function using an instance of HookimplMarker."
                ),
                method,
            )
            res = {}
        return res 
Example #9
Source File: namenode.py    From petastorm with Apache License 2.0 6 votes vote down vote up
def failover_all_class_methods(decorator):
    """
    This decorator function wraps an entire class to decorate each member method, incl. inherited.

    Adapted from https://stackoverflow.com/a/6307868
    """

    # Convenience function to ensure `decorate` gets wrapper function attributes: name, docs, etc.
    @functools.wraps(decorator)
    def decorate(cls):
        all_methods = inspect.getmembers(cls, inspect.isbuiltin) \
            + inspect.getmembers(cls, inspect.ismethod) \
            + inspect.getmembers(cls, inspect.isroutine)
        for name, method in all_methods:
            if not name.startswith('_'):
                # It's safer to exclude all protected/private method from decoration
                setattr(cls, name, decorator(method))
        return cls

    return decorate 
Example #10
Source File: pydoc.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #11
Source File: manager.py    From python-netsurv with MIT License 6 votes vote down vote up
def parse_hookimpl_opts(self, plugin, name):
        method = getattr(plugin, name)
        if not inspect.isroutine(method):
            return
        try:
            res = getattr(method, self.project_name + "_impl", None)
        except Exception:
            res = {}
        if res is not None and not isinstance(res, dict):
            # false positive
            res = None
        # TODO: remove when we drop implprefix in 1.0
        elif res is None and self._implprefix and name.startswith(self._implprefix):
            _warn_for_function(
                DeprecationWarning(
                    "The `implprefix` system is deprecated please decorate "
                    "this function using an instance of HookimplMarker."
                ),
                method,
            )
            res = {}
        return res 
Example #12
Source File: pydoc.py    From meddle with MIT License 6 votes vote down vote up
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) 
Example #13
Source File: pydoc.py    From meddle with MIT License 6 votes vote down vote up
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) 
Example #14
Source File: pydoc.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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) 
Example #15
Source File: pydoc.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #16
Source File: pydoc.py    From BinderFilter with MIT License 6 votes vote down vote up
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) 
Example #17
Source File: pydoc.py    From BinderFilter with MIT License 6 votes vote down vote up
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) 
Example #18
Source File: pydoc.py    From Computable with MIT License 6 votes vote down vote up
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) 
Example #19
Source File: pydoc.py    From Computable with MIT License 6 votes vote down vote up
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) 
Example #20
Source File: pydoc.py    From oss-ftp with MIT License 6 votes vote down vote up
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) 
Example #21
Source File: pydoc.py    From oss-ftp with MIT License 6 votes vote down vote up
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) 
Example #22
Source File: event.py    From flappy-bird-py with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #23
Source File: automodapi.py    From supersmoother with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _mod_info(modname, toskip=[], onlylocals=True):
    """
    Determines if a module is a module or a package and whether or not
    it has classes or functions.
    """

    hascls = hasfunc = False

    for localnm, fqnm, obj in zip(*find_mod_objs(modname, onlylocals=onlylocals)):
        if localnm not in toskip:
            hascls = hascls or inspect.isclass(obj)
            hasfunc = hasfunc or inspect.isroutine(obj)
            if hascls and hasfunc:
                break

    # find_mod_objs has already imported modname
    # TODO: There is probably a cleaner way to do this, though this is pretty
    # reliable for all Python versions for most cases that we care about.
    pkg = sys.modules[modname]
    ispkg = (hasattr(pkg, '__file__') and isinstance(pkg.__file__, str) and
             os.path.split(pkg.__file__)[1].startswith('__init__.py'))

    return ispkg, hascls, hasfunc 
Example #24
Source File: pydoc.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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) 
Example #25
Source File: config.py    From rosetta_recsys2019 with Apache License 2.0 6 votes vote down vote up
def get_attributes(self): 
        attributes = inspect.getmembers(self, lambda a: not (inspect.isroutine(a)))
 
        # store only not the default attribute __xx__
        attribute_tuple_list = [a for a in attributes if not (a[0].startswith('__') and a[0].endswith('__'))]

        attribute_dict = {}
        for tup in attribute_tuple_list:
            key = tup[0]
            value = tup[1]
            if key == 'loss':
                value = str(value)
            # convert numpy value to float
            if type(value) == np.float64:
                value = float(value)
            attribute_dict[key] = value

        return attribute_dict 
Example #26
Source File: pydoc.py    From oss-ftp with MIT License 5 votes vote down vote up
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)) 
Example #27
Source File: autogen.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def collect_class_methods(cls, methods):
    if isinstance(methods, (list, tuple)):
        return [getattr(cls, m) if isinstance(m, str) else m for m in methods]
    methods = []
    for _, method in inspect.getmembers(cls, predicate=inspect.isroutine):
        if method.__name__[0] == '_' or method.__name__ in EXCLUDE:
            continue
        methods.append(method)
    return methods 
Example #28
Source File: pydoc.py    From Computable with MIT License 5 votes vote down vote up
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)) 
Example #29
Source File: __init__.py    From chainer with MIT License 5 votes vote down vote up
def set_doc(obj, docstring):
    if ((inspect.ismethoddescriptor(obj) or inspect.isroutine(obj))
            and not inspect.isfunction(obj)):
        # pybind-generated functions and methods
        _core._set_pybind_doc(obj, docstring)
        return

    obj.__doc__ = docstring 
Example #30
Source File: manager.py    From pmatic with GNU General Public License v2.0 5 votes vote down vote up
def save(cls):
        config = {}

        for key, val in cls.__dict__.items():
            if key[0] != "_" and key not in [ "config_path", "script_path",
                                              "static_path", "log_file" ] \
               and not inspect.isroutine(val):
                config[key] = val

        if not os.path.exists(os.path.dirname(cls._config_path())):
            os.makedirs(os.path.dirname(cls._config_path()))

        json_config = json.dumps(config)
        open(cls._config_path(), "w").write(json_config + "\n")