Python collections.Callable() Examples

The following are code examples for showing how to use collections.Callable(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: shutil.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def register_archive_format(name, function, extra_args=None, description=''):
    """Registers an archive format.

    name is the name of the format. function is the callable that will be
    used to create archives. If provided, extra_args is a sequence of
    (name, value) tuples that will be passed as arguments to the callable.
    description can be provided to describe the format, and will be returned
    by the get_archive_formats() function.
    """
    if extra_args is None:
        extra_args = []
    if not isinstance(function, collections.Callable):
        raise TypeError('The %s object is not callable' % function)
    if not isinstance(extra_args, (tuple, list)):
        raise TypeError('extra_args needs to be a sequence')
    for element in extra_args:
        if not isinstance(element, (tuple, list)) or len(element) !=2 :
            raise TypeError('extra_args elements are : (arg_name, value)')

    _ARCHIVE_FORMATS[name] = (function, extra_args, description) 
Example 2
Project: pyblish-win   Author: pyblish   File: test_collections.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_Callable(self):
        non_samples = [None, 42, 3.14, 1j,
                       "", "".encode('ascii'), (), [], {}, set(),
                       (lambda: (yield))(),
                       (x for x in []),
                       ]
        for x in non_samples:
            self.assertNotIsInstance(x, Callable)
            self.assertFalse(issubclass(type(x), Callable), repr(type(x)))
        samples = [lambda: None,
                   type, int, object,
                   len,
                   list.append, [].append,
                   ]
        for x in samples:
            self.assertIsInstance(x, Callable)
            self.assertTrue(issubclass(type(x), Callable), repr(type(x)))
        self.validate_abstract_methods(Callable, '__call__')
        self.validate_isinstance(Callable, '__call__') 
Example 3
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: shutil.py    MIT License 6 votes vote down vote up
def register_archive_format(name, function, extra_args=None, description=''):
    """Registers an archive format.

    name is the name of the format. function is the callable that will be
    used to create archives. If provided, extra_args is a sequence of
    (name, value) tuples that will be passed as arguments to the callable.
    description can be provided to describe the format, and will be returned
    by the get_archive_formats() function.
    """
    if extra_args is None:
        extra_args = []
    if not isinstance(function, collections.Callable):
        raise TypeError('The %s object is not callable' % function)
    if not isinstance(extra_args, (tuple, list)):
        raise TypeError('extra_args needs to be a sequence')
    for element in extra_args:
        if not isinstance(element, (tuple, list)) or len(element) !=2:
            raise TypeError('extra_args elements are : (arg_name, value)')

    _ARCHIVE_FORMATS[name] = (function, extra_args, description) 
Example 4
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: shutil.py    MIT License 6 votes vote down vote up
def _check_unpack_options(extensions, function, extra_args):
    """Checks what gets registered as an unpacker."""
    # first make sure no other unpacker is registered for this extension
    existing_extensions = {}
    for name, info in _UNPACK_FORMATS.items():
        for ext in info[0]:
            existing_extensions[ext] = name

    for extension in extensions:
        if extension in existing_extensions:
            msg = '%s is already registered for "%s"'
            raise RegistryError(msg % (extension,
                                       existing_extensions[extension]))

    if not isinstance(function, collections.Callable):
        raise TypeError('The registered function must be a callable') 
Example 5
Project: flasky   Author: RoseOu   File: shutil.py    MIT License 6 votes vote down vote up
def register_archive_format(name, function, extra_args=None, description=''):
    """Registers an archive format.

    name is the name of the format. function is the callable that will be
    used to create archives. If provided, extra_args is a sequence of
    (name, value) tuples that will be passed as arguments to the callable.
    description can be provided to describe the format, and will be returned
    by the get_archive_formats() function.
    """
    if extra_args is None:
        extra_args = []
    if not isinstance(function, collections.Callable):
        raise TypeError('The %s object is not callable' % function)
    if not isinstance(extra_args, (tuple, list)):
        raise TypeError('extra_args needs to be a sequence')
    for element in extra_args:
        if not isinstance(element, (tuple, list)) or len(element) !=2:
            raise TypeError('extra_args elements are : (arg_name, value)')

    _ARCHIVE_FORMATS[name] = (function, extra_args, description) 
Example 6
Project: flasky   Author: RoseOu   File: shutil.py    MIT License 6 votes vote down vote up
def _check_unpack_options(extensions, function, extra_args):
    """Checks what gets registered as an unpacker."""
    # first make sure no other unpacker is registered for this extension
    existing_extensions = {}
    for name, info in _UNPACK_FORMATS.items():
        for ext in info[0]:
            existing_extensions[ext] = name

    for extension in extensions:
        if extension in existing_extensions:
            msg = '%s is already registered for "%s"'
            raise RegistryError(msg % (extension,
                                       existing_extensions[extension]))

    if not isinstance(function, collections.Callable):
        raise TypeError('The registered function must be a callable') 
Example 7
Project: sic   Author: Yanixos   File: shutil.py    GNU General Public License v3.0 6 votes vote down vote up
def register_archive_format(name, function, extra_args=None, description=''):
    """Registers an archive format.

    name is the name of the format. function is the callable that will be
    used to create archives. If provided, extra_args is a sequence of
    (name, value) tuples that will be passed as arguments to the callable.
    description can be provided to describe the format, and will be returned
    by the get_archive_formats() function.
    """
    if extra_args is None:
        extra_args = []
    if not isinstance(function, collections.Callable):
        raise TypeError('The %s object is not callable' % function)
    if not isinstance(extra_args, (tuple, list)):
        raise TypeError('extra_args needs to be a sequence')
    for element in extra_args:
        if not isinstance(element, (tuple, list)) or len(element) !=2:
            raise TypeError('extra_args elements are : (arg_name, value)')

    _ARCHIVE_FORMATS[name] = (function, extra_args, description) 
Example 8
Project: sic   Author: Yanixos   File: shutil.py    GNU General Public License v3.0 6 votes vote down vote up
def _check_unpack_options(extensions, function, extra_args):
    """Checks what gets registered as an unpacker."""
    # first make sure no other unpacker is registered for this extension
    existing_extensions = {}
    for name, info in _UNPACK_FORMATS.items():
        for ext in info[0]:
            existing_extensions[ext] = name

    for extension in extensions:
        if extension in existing_extensions:
            msg = '%s is already registered for "%s"'
            raise RegistryError(msg % (extension,
                                       existing_extensions[extension]))

    if not isinstance(function, collections.Callable):
        raise TypeError('The registered function must be a callable') 
Example 9
Project: face_rekognition   Author: cnidus   File: Image.py    GNU General Public License v3.0 6 votes vote down vote up
def filter(self, filter):
        """
        Filters this image using the given filter.  For a list of
        available filters, see the :py:mod:`~PIL.ImageFilter` module.

        :param filter: Filter kernel.
        :returns: An :py:class:`~PIL.Image.Image` object.  """

        self.load()

        if isinstance(filter, collections.Callable):
            filter = filter()
        if not hasattr(filter, "filter"):
            raise TypeError("filter argument should be ImageFilter.Filter " +
                            "instance or class")

        if self.im.bands == 1:
            return self._new(filter.filter(self.im))
        # fix to handle multiband images since _imaging doesn't
        ims = []
        for c in range(self.im.bands):
            ims.append(self._new(filter.filter(self.im.getband(c))))
        return merge(self.mode, ims) 
Example 10
Project: AshsSDK   Author: thehappydinoa   File: shutil.py    MIT License 6 votes vote down vote up
def register_archive_format(name, function, extra_args=None, description=''):
    """Registers an archive format.

    name is the name of the format. function is the callable that will be
    used to create archives. If provided, extra_args is a sequence of
    (name, value) tuples that will be passed as arguments to the callable.
    description can be provided to describe the format, and will be returned
    by the get_archive_formats() function.
    """
    if extra_args is None:
        extra_args = []
    if not isinstance(function, collections.Callable):
        raise TypeError('The %s object is not callable' % function)
    if not isinstance(extra_args, (tuple, list)):
        raise TypeError('extra_args needs to be a sequence')
    for element in extra_args:
        if not isinstance(element, (tuple, list)) or len(element) !=2:
            raise TypeError('extra_args elements are : (arg_name, value)')

    _ARCHIVE_FORMATS[name] = (function, extra_args, description) 
Example 11
Project: AshsSDK   Author: thehappydinoa   File: shutil.py    MIT License 6 votes vote down vote up
def _check_unpack_options(extensions, function, extra_args):
    """Checks what gets registered as an unpacker."""
    # first make sure no other unpacker is registered for this extension
    existing_extensions = {}
    for name, info in _UNPACK_FORMATS.items():
        for ext in info[0]:
            existing_extensions[ext] = name

    for extension in extensions:
        if extension in existing_extensions:
            msg = '%s is already registered for "%s"'
            raise RegistryError(msg % (extension,
                                       existing_extensions[extension]))

    if not isinstance(function, collections.Callable):
        raise TypeError('The registered function must be a callable') 
Example 12
Project: stfinv   Author: seismology   File: numpydoc.py    GNU General Public License v3.0 6 votes vote down vote up
def mangle_signature(app, what, name, obj, options, sig, retann):
    # Do not try to inspect classes that don't define `__init__`
    if (inspect.isclass(obj) and
        (not hasattr(obj, '__init__') or
            'initializes x; see ' in pydoc.getdoc(obj.__init__))):
        return '', ''

    if not (isinstance(obj, collections.Callable) or
            hasattr(obj, '__argspec_is_invalid_')):
        return

    if not hasattr(obj, '__doc__'):
        return

    doc = SphinxDocString(pydoc.getdoc(obj))
    if doc['Signature']:
        sig = re.sub(sixu("^[^(]*"), sixu(""), doc['Signature'])
        return sig, sixu('') 
Example 13
Project: annsa   Author: arfc   File: numpydoc.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def mangle_signature(app, what, name, obj, options, sig, retann):
    # Do not try to inspect classes that don't define `__init__`
    if (inspect.isclass(obj) and
        (not hasattr(obj, '__init__') or
            'initializes x; see ' in pydoc.getdoc(obj.__init__))):
        return '', ''

    if not (isinstance(obj, collections.Callable) or
            hasattr(obj, '__argspec_is_invalid_')):
        return

    if not hasattr(obj, '__doc__'):
        return

    doc = SphinxDocString(pydoc.getdoc(obj))
    if doc['Signature']:
        sig = re.sub(sixu("^[^(]*"), sixu(""), doc['Signature'])
        return sig, sixu('') 
Example 14
Project: Repobot   Author: Desgard   File: shutil.py    MIT License 6 votes vote down vote up
def register_archive_format(name, function, extra_args=None, description=''):
    """Registers an archive format.

    name is the name of the format. function is the callable that will be
    used to create archives. If provided, extra_args is a sequence of
    (name, value) tuples that will be passed as arguments to the callable.
    description can be provided to describe the format, and will be returned
    by the get_archive_formats() function.
    """
    if extra_args is None:
        extra_args = []
    if not isinstance(function, collections.Callable):
        raise TypeError('The %s object is not callable' % function)
    if not isinstance(extra_args, (tuple, list)):
        raise TypeError('extra_args needs to be a sequence')
    for element in extra_args:
        if not isinstance(element, (tuple, list)) or len(element) !=2:
            raise TypeError('extra_args elements are : (arg_name, value)')

    _ARCHIVE_FORMATS[name] = (function, extra_args, description) 
Example 15
Project: Repobot   Author: Desgard   File: shutil.py    MIT License 6 votes vote down vote up
def _check_unpack_options(extensions, function, extra_args):
    """Checks what gets registered as an unpacker."""
    # first make sure no other unpacker is registered for this extension
    existing_extensions = {}
    for name, info in _UNPACK_FORMATS.items():
        for ext in info[0]:
            existing_extensions[ext] = name

    for extension in extensions:
        if extension in existing_extensions:
            msg = '%s is already registered for "%s"'
            raise RegistryError(msg % (extension,
                                       existing_extensions[extension]))

    if not isinstance(function, collections.Callable):
        raise TypeError('The registered function must be a callable') 
Example 16
Project: graph-keyword-search   Author: usc-isi-i2   File: util.py    Apache License 2.0 6 votes vote down vote up
def info(object, spacing=12, collapse=1, hidden=False, dest=sys.stdout):
    """Print methods and doc strings.
Takes module, class, list, dictionary, or string."""
    print("INFO for %r" % (object), file=dest)
    methodList = [e for e in dir(object) if isinstance(safeGetAttr(object, e), collections.Callable)]
    processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
    print("\n".join(["  %s %s" % (method.ljust(spacing),
                                processFunc(str(safeGetAttr(object, method).__doc__)))
                    for method in methodList
                    if hidden or not method.startswith("__")]), file=dest)
    attrList = [e for e in dir(object) if not isinstance(safeGetAttr(object, e), collections.Callable)]
    print("\n".join(["  %s %s" % (attr.ljust(spacing),
                                processFunc(str(safeGetAttr(object, attr))))
                    for attr in attrList
                    if hidden or not attr.startswith("__")]), file=dest)
    print("END INFO for %r" % (object), file=dest)

# if name == "main": print help.doc 

# util section data-directed programming 
Example 17
Project: JukeBox   Author: gauravsarkar97   File: shutil.py    MIT License 6 votes vote down vote up
def register_archive_format(name, function, extra_args=None, description=''):
    """Registers an archive format.

    name is the name of the format. function is the callable that will be
    used to create archives. If provided, extra_args is a sequence of
    (name, value) tuples that will be passed as arguments to the callable.
    description can be provided to describe the format, and will be returned
    by the get_archive_formats() function.
    """
    if extra_args is None:
        extra_args = []
    if not isinstance(function, collections.Callable):
        raise TypeError('The %s object is not callable' % function)
    if not isinstance(extra_args, (tuple, list)):
        raise TypeError('extra_args needs to be a sequence')
    for element in extra_args:
        if not isinstance(element, (tuple, list)) or len(element) !=2:
            raise TypeError('extra_args elements are : (arg_name, value)')

    _ARCHIVE_FORMATS[name] = (function, extra_args, description) 
Example 18
Project: JukeBox   Author: gauravsarkar97   File: shutil.py    MIT License 6 votes vote down vote up
def _check_unpack_options(extensions, function, extra_args):
    """Checks what gets registered as an unpacker."""
    # first make sure no other unpacker is registered for this extension
    existing_extensions = {}
    for name, info in _UNPACK_FORMATS.items():
        for ext in info[0]:
            existing_extensions[ext] = name

    for extension in extensions:
        if extension in existing_extensions:
            msg = '%s is already registered for "%s"'
            raise RegistryError(msg % (extension,
                                       existing_extensions[extension]))

    if not isinstance(function, collections.Callable):
        raise TypeError('The registered function must be a callable') 
Example 19
Project: chattR   Author: patrickstocklin   File: shutil.py    GNU General Public License v2.0 6 votes vote down vote up
def register_archive_format(name, function, extra_args=None, description=''):
    """Registers an archive format.

    name is the name of the format. function is the callable that will be
    used to create archives. If provided, extra_args is a sequence of
    (name, value) tuples that will be passed as arguments to the callable.
    description can be provided to describe the format, and will be returned
    by the get_archive_formats() function.
    """
    if extra_args is None:
        extra_args = []
    if not isinstance(function, collections.Callable):
        raise TypeError('The %s object is not callable' % function)
    if not isinstance(extra_args, (tuple, list)):
        raise TypeError('extra_args needs to be a sequence')
    for element in extra_args:
        if not isinstance(element, (tuple, list)) or len(element) !=2:
            raise TypeError('extra_args elements are : (arg_name, value)')

    _ARCHIVE_FORMATS[name] = (function, extra_args, description) 
Example 20
Project: chattR   Author: patrickstocklin   File: shutil.py    GNU General Public License v2.0 6 votes vote down vote up
def _check_unpack_options(extensions, function, extra_args):
    """Checks what gets registered as an unpacker."""
    # first make sure no other unpacker is registered for this extension
    existing_extensions = {}
    for name, info in _UNPACK_FORMATS.items():
        for ext in info[0]:
            existing_extensions[ext] = name

    for extension in extensions:
        if extension in existing_extensions:
            msg = '%s is already registered for "%s"'
            raise RegistryError(msg % (extension,
                                       existing_extensions[extension]))

    if not isinstance(function, collections.Callable):
        raise TypeError('The registered function must be a callable') 
Example 21
Project: TornadoWeb   Author: VxCoder   File: client.py    Apache License 2.0 6 votes vote down vote up
def __getattribute__(self, item):
        """
        Bind methods to the weak proxy to avoid memory leaks
        when bound method is passed as argument to the gen.Task
        constructor.
        """
        a = super(Client, self).__getattribute__(item)
        try:
            if isinstance(a, collections.Callable) and a.__self__:
                try:
                    a = self.__class__.__dict__[item]
                except KeyError:
                    a = Client.__dict__[item]
                a = partial(a, self._weak)
        except AttributeError:
            pass
        return a 
Example 22
Project: Flask_Blog   Author: sugarguo   File: shutil.py    GNU General Public License v3.0 6 votes vote down vote up
def register_archive_format(name, function, extra_args=None, description=''):
    """Registers an archive format.

    name is the name of the format. function is the callable that will be
    used to create archives. If provided, extra_args is a sequence of
    (name, value) tuples that will be passed as arguments to the callable.
    description can be provided to describe the format, and will be returned
    by the get_archive_formats() function.
    """
    if extra_args is None:
        extra_args = []
    if not isinstance(function, collections.Callable):
        raise TypeError('The %s object is not callable' % function)
    if not isinstance(extra_args, (tuple, list)):
        raise TypeError('extra_args needs to be a sequence')
    for element in extra_args:
        if not isinstance(element, (tuple, list)) or len(element) !=2:
            raise TypeError('extra_args elements are : (arg_name, value)')

    _ARCHIVE_FORMATS[name] = (function, extra_args, description) 
Example 23
Project: Flask_Blog   Author: sugarguo   File: shutil.py    GNU General Public License v3.0 6 votes vote down vote up
def _check_unpack_options(extensions, function, extra_args):
    """Checks what gets registered as an unpacker."""
    # first make sure no other unpacker is registered for this extension
    existing_extensions = {}
    for name, info in _UNPACK_FORMATS.items():
        for ext in info[0]:
            existing_extensions[ext] = name

    for extension in extensions:
        if extension in existing_extensions:
            msg = '%s is already registered for "%s"'
            raise RegistryError(msg % (extension,
                                       existing_extensions[extension]))

    if not isinstance(function, collections.Callable):
        raise TypeError('The registered function must be a callable') 
Example 24
Project: pyblish-win   Author: pyblish   File: test_fixers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_prefix_preservation(self):
        b = """callable(    x)"""
        a = """import collections\nisinstance(    x, collections.Callable)"""
        self.check(b, a)

        b = """if     callable(x): pass"""
        a = """import collections
if     isinstance(x, collections.Callable): pass"""
        self.check(b, a) 
Example 25
Project: pyblish-win   Author: pyblish   File: test_fixers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_callable_call(self):
        b = """callable(x)"""
        a = """import collections\nisinstance(x, collections.Callable)"""
        self.check(b, a) 
Example 26
Project: pyblish-win   Author: pyblish   File: test_collections.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_registration(self):
        for B in Hashable, Iterable, Iterator, Sized, Container, Callable:
            class C:
                __metaclass__ = type
                __hash__ = None  # Make sure it isn't hashable by default
            self.assertFalse(issubclass(C, B), B.__name__)
            B.register(C)
            self.assertTrue(issubclass(C, B)) 
Example 27
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: misc.py    MIT License 5 votes vote down vote up
def callable(obj):
        return isinstance(obj, Callable) 
Example 28
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: compat.py    MIT License 5 votes vote down vote up
def callable(obj):
        return isinstance(obj, Callable) 
Example 29
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: models.py    MIT License 5 votes vote down vote up
def register_hook(self, event, hook):
        """Properly register a hook."""

        if event not in self.hooks:
            raise ValueError('Unsupported event specified, with event name "%s"' % (event))

        if isinstance(hook, collections.Callable):
            self.hooks[event].append(hook)
        elif hasattr(hook, '__iter__'):
            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) 
Example 30
Project: flasky   Author: RoseOu   File: misc.py    MIT License 5 votes vote down vote up
def callable(obj):
        return isinstance(obj, Callable) 
Example 31
Project: flasky   Author: RoseOu   File: compat.py    MIT License 5 votes vote down vote up
def callable(obj):
        return isinstance(obj, Callable) 
Example 32
Project: flasky   Author: RoseOu   File: models.py    MIT License 5 votes vote down vote up
def register_hook(self, event, hook):
        """Properly register a hook."""

        if event not in self.hooks:
            raise ValueError('Unsupported event specified, with event name "%s"' % (event))

        if isinstance(hook, collections.Callable):
            self.hooks[event].append(hook)
        elif hasattr(hook, '__iter__'):
            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) 
Example 33
Project: sic   Author: Yanixos   File: misc.py    GNU General Public License v3.0 5 votes vote down vote up
def callable(obj):
        return isinstance(obj, Callable) 
Example 34
Project: sic   Author: Yanixos   File: compat.py    GNU General Public License v3.0 5 votes vote down vote up
def callable(obj):
        return isinstance(obj, Callable) 
Example 35
Project: sic   Author: Yanixos   File: models.py    GNU General Public License v3.0 5 votes vote down vote up
def register_hook(self, event, hook):
        """Properly register a hook."""

        if event not in self.hooks:
            raise ValueError('Unsupported event specified, with event name "%s"' % (event))

        if isinstance(hook, collections.Callable):
            self.hooks[event].append(hook)
        elif hasattr(hook, '__iter__'):
            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) 
Example 36
Project: bigquerylayers   Author: smandaric   File: calling.py    GNU General Public License v3.0 5 votes vote down vote up
def callable(x):
        return isinstance(x, collections.Callable) 
Example 37
Project: AshsSDK   Author: thehappydinoa   File: misc.py    MIT License 5 votes vote down vote up
def callable(obj):
        return isinstance(obj, Callable) 
Example 38
Project: AshsSDK   Author: thehappydinoa   File: compat.py    MIT License 5 votes vote down vote up
def callable(obj):
        return isinstance(obj, Callable) 
Example 39
Project: AshsSDK   Author: thehappydinoa   File: models.py    MIT License 5 votes vote down vote up
def register_hook(self, event, hook):
        """Properly register a hook."""

        if event not in self.hooks:
            raise ValueError('Unsupported event specified, with event name "%s"' % (event))

        if isinstance(hook, collections.Callable):
            self.hooks[event].append(hook)
        elif hasattr(hook, '__iter__'):
            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) 
Example 40
Project: stfinv   Author: seismology   File: docscrape.py    GNU General Public License v3.0 5 votes vote down vote up
def methods(self):
        if self._cls is None:
            return []
        return [name for name, func in inspect.getmembers(self._cls)
                if ((not name.startswith('_')
                     or name in self.extra_public_methods)
                    and isinstance(func, collections.Callable)
                    and self._is_show_member(name))] 
Example 41
Project: Kitsu.Bundle   Author: AeonLucid   File: models.py    MIT License 5 votes vote down vote up
def register_hook(self, event, hook):
        """Properly register a hook."""

        if event not in self.hooks:
            raise ValueError('Unsupported event specified, with event name "%s"' % (event))

        if isinstance(hook, collections.Callable):
            self.hooks[event].append(hook)
        elif hasattr(hook, '__iter__'):
            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) 
Example 42
Project: annsa   Author: arfc   File: docscrape.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def methods(self):
        if self._cls is None:
            return []
        return [name for name, func in inspect.getmembers(self._cls)
                if ((not name.startswith('_')
                     or name in self.extra_public_methods)
                    and isinstance(func, collections.Callable)
                    and self._is_show_member(name))] 
Example 43
Project: matchminer-engine   Author: dfci   File: schema.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _validate_type_callable(self, value):
        if isinstance(value, Callable):
            return True 
Example 44
Project: matchminer-engine   Author: dfci   File: schema.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _validator_handler(self, field, value):
        if isinstance(value, Callable):
            return
        if isinstance(value, _str_type):
            if value not in self.target_validator.validators and \
                    value not in self.target_validator.coercers:
                self._error(field, '%s is no valid coercer' % value)
        elif isinstance(value, Iterable):
            for handler in value:
                self._validator_handler(field, handler) 
Example 45
Project: jawfish   Author: war-and-code   File: models.py    MIT License 5 votes vote down vote up
def register_hook(self, event, hook):
        """Properly register a hook."""

        if event not in self.hooks:
            raise ValueError('Unsupported event specified, with event name "%s"' % (event))

        if isinstance(hook, collections.Callable):
            self.hooks[event].append(hook)
        elif hasattr(hook, '__iter__'):
            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) 
Example 46
Project: Repobot   Author: Desgard   File: misc.py    MIT License 5 votes vote down vote up
def callable(obj):
        return isinstance(obj, Callable) 
Example 47
Project: Repobot   Author: Desgard   File: compat.py    MIT License 5 votes vote down vote up
def callable(obj):
        return isinstance(obj, Callable) 
Example 48
Project: Repobot   Author: Desgard   File: models.py    MIT License 5 votes vote down vote up
def register_hook(self, event, hook):
        """Properly register a hook."""

        if event not in self.hooks:
            raise ValueError('Unsupported event specified, with event name "%s"' % (event))

        if isinstance(hook, collections.Callable):
            self.hooks[event].append(hook)
        elif hasattr(hook, '__iter__'):
            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) 
Example 49
Project: graph-keyword-search   Author: usc-isi-i2   File: util.py    Apache License 2.0 5 votes vote down vote up
def vanillaRepr(o):
    cr = hasattr(o, "signature") and isinstance(getattr(o, "signature"), collections.Callable) and o.signature()
    cr = "'%s' " % (cr) if cr else ''
    return "{|%s %[email protected] %s|}" % (fullyQualifiedName(o), cr, base36encode(id(o))) 
Example 50
Project: graph-keyword-search   Author: usc-isi-i2   File: util.py    Apache License 2.0 5 votes vote down vote up
def vanillaStr(o):
    cr = hasattr(o, "signature") and isinstance(getattr(o, "signature"), collections.Callable) and o.signature()
    cr = "%s " % (cr) if cr else ''
    return emittable("<%s %[email protected] %s>" % (fullyQualifiedName(o), cr, base36encode(id(o)))) 
Example 51
Project: lena   Author: coingraham   File: models.py    MIT License 5 votes vote down vote up
def register_hook(self, event, hook):
        """Properly register a hook."""

        if event not in self.hooks:
            raise ValueError('Unsupported event specified, with event name "%s"' % (event))

        if isinstance(hook, collections.Callable):
            self.hooks[event].append(hook)
        elif hasattr(hook, '__iter__'):
            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) 
Example 52
Project: rebel-framework   Author: reb311ion   File: models.py    GNU General Public License v3.0 5 votes vote down vote up
def register_hook(self, event, hook):
        """Properly register a hook."""

        if event not in self.hooks:
            raise ValueError('Unsupported event specified, with event name "%s"' % (event))

        if isinstance(hook, collections.Callable):
            self.hooks[event].append(hook)
        elif hasattr(hook, '__iter__'):
            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) 
Example 53
Project: rebel-framework   Author: reb311ion   File: element.py    GNU General Public License v3.0 5 votes vote down vote up
def search_tag(self, markup_name=None, markup_attrs={}):
        found = None
        markup = None
        if isinstance(markup_name, Tag):
            markup = markup_name
            markup_attrs = markup
        call_function_with_tag_data = (
            isinstance(self.name, collections.Callable)
            and not isinstance(markup_name, Tag))

        if ((not self.name)
            or call_function_with_tag_data
            or (markup and self._matches(markup, self.name))
            or (not markup and self._matches(markup_name, self.name))):
            if call_function_with_tag_data:
                match = self.name(markup_name, markup_attrs)
            else:
                match = True
                markup_attr_map = None
                for attr, match_against in list(self.attrs.items()):
                    if not markup_attr_map:
                        if hasattr(markup_attrs, 'get'):
                            markup_attr_map = markup_attrs
                        else:
                            markup_attr_map = {}
                            for k, v in markup_attrs:
                                markup_attr_map[k] = v
                    attr_value = markup_attr_map.get(attr)
                    if not self._matches(attr_value, match_against):
                        match = False
                        break
            if match:
                if markup:
                    found = markup
                else:
                    found = markup_name
        if found and self.text and not self._matches(found.string, self.text):
            found = None
        return found 
Example 54
Project: rebel-framework   Author: reb311ion   File: _lxml.py    GNU General Public License v3.0 5 votes vote down vote up
def parser_for(self, encoding):
        # Use the default parser.
        parser = self.default_parser(encoding)

        if isinstance(parser, collections.Callable):
            # Instantiate the parser with default arguments
            parser = parser(target=self, strip_cdata=False, encoding=encoding)
        return parser 
Example 55
Project: Pesterchum   Author: henry232323   File: client.py    MIT License 5 votes vote down vote up
def addTimer(self, seconds, cb):
        """ add a timed callback. accuracy is not specified, you can only
        garuntee the callback will be called after seconds has passed.
        ( the only advantage to these timers is they dont use threads )
        """
        assert isinstance(cb, collections.Callable)
        logging.info('added timer to call %s in %ss' % (cb, seconds))
        self._timers.append((time.time() + seconds, cb)) 
Example 56
Project: JukeBox   Author: gauravsarkar97   File: misc.py    MIT License 5 votes vote down vote up
def callable(obj):
        return isinstance(obj, Callable) 
Example 57
Project: JukeBox   Author: gauravsarkar97   File: compat.py    MIT License 5 votes vote down vote up
def callable(obj):
        return isinstance(obj, Callable) 
Example 58
Project: JukeBox   Author: gauravsarkar97   File: models.py    MIT License 5 votes vote down vote up
def register_hook(self, event, hook):
        """Properly register a hook."""

        if event not in self.hooks:
            raise ValueError('Unsupported event specified, with event name "%s"' % (event))

        if isinstance(hook, collections.Callable):
            self.hooks[event].append(hook)
        elif hasattr(hook, '__iter__'):
            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) 
Example 59
Project: misp42splunk   Author: remg427   File: models.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def register_hook(self, event, hook):
        """Properly register a hook."""

        if event not in self.hooks:
            raise ValueError('Unsupported event specified, with event name "%s"' % (event))

        if isinstance(hook, collections.Callable):
            self.hooks[event].append(hook)
        elif hasattr(hook, '__iter__'):
            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) 
Example 60
Project: misp42splunk   Author: remg427   File: models.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def register_hook(self, event, hook):
        """Properly register a hook."""

        if event not in self.hooks:
            raise ValueError('Unsupported event specified, with event name "%s"' % (event))

        if isinstance(hook, collections.Callable):
            self.hooks[event].append(hook)
        elif hasattr(hook, '__iter__'):
            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) 
Example 61
Project: chattR   Author: patrickstocklin   File: misc.py    GNU General Public License v2.0 5 votes vote down vote up
def callable(obj):
        return isinstance(obj, Callable) 
Example 62
Project: chattR   Author: patrickstocklin   File: compat.py    GNU General Public License v2.0 5 votes vote down vote up
def callable(obj):
        return isinstance(obj, Callable) 
Example 63
Project: chattR   Author: patrickstocklin   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def register_hook(self, event, hook):
        """Properly register a hook."""

        if event not in self.hooks:
            raise ValueError('Unsupported event specified, with event name "%s"' % (event))

        if isinstance(hook, collections.Callable):
            self.hooks[event].append(hook)
        elif hasattr(hook, '__iter__'):
            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) 
Example 64
Project: Attention-Gated-Networks   Author: ozan-oktay   File: util.py    MIT License 5 votes vote down vote up
def info(object, spacing=10, collapse=1):
    """Print methods and doc strings.
    Takes module, class, list, dictionary, or string."""
    methodList = [e for e in dir(object) if isinstance(getattr(object, e), collections.Callable)]
    processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
    print( "\n".join(["%s %s" %
                     (method.ljust(spacing),
                      processFunc(str(getattr(object, method).__doc__)))
                     for method in methodList]) ) 
Example 65
Project: analyzer-website   Author: santiagolizardo   File: element.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def search_tag(self, markup_name=None, markup_attrs={}):
        found = None
        markup = None
        if isinstance(markup_name, Tag):
            markup = markup_name
            markup_attrs = markup
        call_function_with_tag_data = (
            isinstance(self.name, collections.Callable)
            and not isinstance(markup_name, Tag))

        if ((not self.name)
            or call_function_with_tag_data
            or (markup and self._matches(markup, self.name))
            or (not markup and self._matches(markup_name, self.name))):
            if call_function_with_tag_data:
                match = self.name(markup_name, markup_attrs)
            else:
                match = True
                markup_attr_map = None
                for attr, match_against in list(self.attrs.items()):
                    if not markup_attr_map:
                        if hasattr(markup_attrs, 'get'):
                            markup_attr_map = markup_attrs
                        else:
                            markup_attr_map = {}
                            for k, v in markup_attrs:
                                markup_attr_map[k] = v
                    attr_value = markup_attr_map.get(attr)
                    if not self._matches(attr_value, match_against):
                        match = False
                        break
            if match:
                if markup:
                    found = markup
                else:
                    found = markup_name
        if found and self.text and not self._matches(found.string, self.text):
            found = None
        return found 
Example 66
Project: analyzer-website   Author: santiagolizardo   File: _lxml.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def parser_for(self, encoding):
        # Use the default parser.
        parser = self.default_parser(encoding)

        if isinstance(parser, collections.Callable):
            # Instantiate the parser with default arguments
            parser = parser(target=self, strip_cdata=False, encoding=encoding)
        return parser 
Example 67
Project: Flask_Blog   Author: sugarguo   File: misc.py    GNU General Public License v3.0 5 votes vote down vote up
def callable(obj):
        return isinstance(obj, Callable) 
Example 68
Project: Flask_Blog   Author: sugarguo   File: compat.py    GNU General Public License v3.0 5 votes vote down vote up
def callable(obj):
        return isinstance(obj, Callable) 
Example 69
Project: Flask_Blog   Author: sugarguo   File: models.py    GNU General Public License v3.0 5 votes vote down vote up
def register_hook(self, event, hook):
        """Properly register a hook."""

        if event not in self.hooks:
            raise ValueError('Unsupported event specified, with event name "%s"' % (event))

        if isinstance(hook, collections.Callable):
            self.hooks[event].append(hook)
        elif hasattr(hook, '__iter__'):
            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) 
Example 70
Project: aws_python_messenger   Author: AdamSpannbauer   File: models.py    MIT License 5 votes vote down vote up
def register_hook(self, event, hook):
        """Properly register a hook."""

        if event not in self.hooks:
            raise ValueError('Unsupported event specified, with event name "%s"' % (event))

        if isinstance(hook, collections.Callable):
            self.hooks[event].append(hook)
        elif hasattr(hook, '__iter__'):
            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) 
Example 71
Project: aws_python_messenger   Author: AdamSpannbauer   File: models.py    MIT License 5 votes vote down vote up
def register_hook(self, event, hook):
        """Properly register a hook."""

        if event not in self.hooks:
            raise ValueError('Unsupported event specified, with event name "%s"' % (event))

        if isinstance(hook, collections.Callable):
            self.hooks[event].append(hook)
        elif hasattr(hook, '__iter__'):
            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) 
Example 72
Project: LaserTOF   Author: kyleuckert   File: test_defmatrix.py    MIT License 5 votes vote down vote up
def test_instance_methods(self):
        a = matrix([1.0], dtype='f8')
        methodargs = {
            'astype': ('intc',),
            'clip': (0.0, 1.0),
            'compress': ([1],),
            'repeat': (1,),
            'reshape': (1,),
            'swapaxes': (0, 0),
            'dot': np.array([1.0]),
            }
        excluded_methods = [
            'argmin', 'choose', 'dump', 'dumps', 'fill', 'getfield',
            'getA', 'getA1', 'item', 'nonzero', 'put', 'putmask', 'resize',
            'searchsorted', 'setflags', 'setfield', 'sort',
            'partition', 'argpartition',
            'take', 'tofile', 'tolist', 'tostring', 'tobytes', 'all', 'any',
            'sum', 'argmax', 'argmin', 'min', 'max', 'mean', 'var', 'ptp',
            'prod', 'std', 'ctypes', 'itemset',
            ]
        for attrib in dir(a):
            if attrib.startswith('_') or attrib in excluded_methods:
                continue
            f = getattr(a, attrib)
            if isinstance(f, collections.Callable):
                # reset contents of a
                a.astype('f8')
                a.fill(1.0)
                if attrib in methodargs:
                    args = methodargs[attrib]
                else:
                    args = ()
                b = f(*args)
                assert_(type(b) is matrix, "%s" % attrib)
        assert_(type(a.real) is matrix)
        assert_(type(a.imag) is matrix)
        c, d = matrix([0.0]).nonzero()
        assert_(type(c) is np.ndarray)
        assert_(type(d) is np.ndarray) 
Example 73
Project: LaserTOF   Author: kyleuckert   File: test_records.py    MIT License 5 votes vote down vote up
def test_recarray_conflict_fields(self):
        ra = np.rec.array([(1, 'abc', 2.3), (2, 'xyz', 4.2),
                        (3, 'wrs', 1.3)],
                       names='field, shape, mean')
        ra.mean = [1.1, 2.2, 3.3]
        assert_array_almost_equal(ra['mean'], [1.1, 2.2, 3.3])
        assert_(type(ra.mean) is type(ra.var))
        ra.shape = (1, 3)
        assert_(ra.shape == (1, 3))
        ra.shape = ['A', 'B', 'C']
        assert_array_equal(ra['shape'], [['A', 'B', 'C']])
        ra.field = 5
        assert_array_equal(ra['field'], [[5, 5, 5]])
        assert_(isinstance(ra.field, collections.Callable)) 
Example 74
Project: core   Author: getavalon   File: models.py    MIT License 5 votes vote down vote up
def register_hook(self, event, hook):
        """Properly register a hook."""

        if event not in self.hooks:
            raise ValueError('Unsupported event specified, with event name "%s"' % (event))

        if isinstance(hook, collections.Callable):
            self.hooks[event].append(hook)
        elif hasattr(hook, '__iter__'):
            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable)) 
Example 75
Project: pyblish-win   Author: pyblish   File: test_fixers.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_global_import(self):
        b = """
def spam(foo):
    callable(foo)"""[1:]
        a = """
import collections
def spam(foo):
    isinstance(foo, collections.Callable)"""[1:]
        self.check(b, a)

        b = """
import collections
def spam(foo):
    callable(foo)"""[1:]
        # same output if it was already imported
        self.check(b, a)

        b = """
from collections import *
def spam(foo):
    callable(foo)"""[1:]
        a = """
from collections import *
import collections
def spam(foo):
    isinstance(foo, collections.Callable)"""[1:]
        self.check(b, a)

        b = """
do_stuff()
do_some_other_stuff()
assert callable(do_stuff)"""[1:]
        a = """
import collections
do_stuff()
do_some_other_stuff()
assert isinstance(do_stuff, collections.Callable)"""[1:]
        self.check(b, a)

        b = """
if isinstance(do_stuff, Callable):
    assert callable(do_stuff)
    do_stuff(do_stuff)
    if not callable(do_stuff):
        exit(1)
    else:
        assert callable(do_stuff)
else:
    assert not callable(do_stuff)"""[1:]
        a = """
import collections
if isinstance(do_stuff, Callable):
    assert isinstance(do_stuff, collections.Callable)
    do_stuff(do_stuff)
    if not isinstance(do_stuff, collections.Callable):
        exit(1)
    else:
        assert isinstance(do_stuff, collections.Callable)
else:
    assert not isinstance(do_stuff, collections.Callable)"""[1:]
        self.check(b, a) 
Example 76
Project: DataHack2018   Author: InnovizTech   File: vis.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def color_pc(self, pc, coloring='reflectivity_and_label', colormap='pc_cmap'):
        """
        Generate coloring for point cloud based on multiple options
        :param pc: point cloud
        :param coloring: Coloring option. Supported: 'reflectivity', np.array of point cloud size x 4 with points colors
        :return:
        """
        if colormap is 'pc_cmap':
            colormap = pc_cmap

        points = pc[:, :3]
        color = np.zeros((len(pc), 4))
        color[:, -1] = 1.

        if isinstance(coloring, np.ndarray) and coloring.dtype == np.int and coloring.shape == (points.shape[0],):
            cmap = ListedColormap(
                ['w', 'magenta', 'orange', 'mediumspringgreen', 'deepskyblue', 'pink', 'y', 'g', 'r', 'purple', ])
            coloring = np.mod(coloring, len(cmap.colors))
            c = cm.ScalarMappable(cmap=cmap, norm=mcolors.Normalize(vmin=0, vmax=len(cmap.colors)-1))
            color = c.to_rgba(coloring)
        elif isinstance(coloring, np.ndarray):
            if coloring.shape == (points.shape[0], 4):
                color = coloring
            if coloring.shape == (points.shape[0], ):
                c = cm.ScalarMappable(cmap=colormap)
                color = c.to_rgba(coloring, norm=False)
        elif isinstance(coloring, collections.Callable):
            colors = coloring(points)
            c = cm.ScalarMappable(cmap=colormap)
            color = c.to_rgba(colors)
        elif coloring == 'reflectivity':
            reflectivity = pc[:, 3]
            reflectivity[reflectivity > 1] = 1
            c = cm.ScalarMappable(cmap=colormap)
            color = c.to_rgba(reflectivity, norm=False)
            color[reflectivity < 0] = np.array([1.0, 1.0, 1.0, 1.0])
        elif coloring == 'reflectivity_and_label':
            # pc_colors
            reflectivity = pc[:, 3]
            reflectivity[reflectivity > 1] = 1
            c = cm.ScalarMappable(cmap=colormap)
            color = c.to_rgba(reflectivity, norm=False)
            if pc.shape[-1] == 5:
                labels = pc[:, 4]
                labels_valid = labels[labels > 0]
                c = cm.ScalarMappable(cmap=label_cmap)
                color_labels = c.to_rgba(labels_valid, norm=True)
                color[labels > 0] = color_labels
        else:
            color = np.ones((points.shape[0], 4))
            color[:, -1] = 1.
        return color 
Example 77
Project: rebel-framework   Author: reb311ion   File: element.py    GNU General Public License v3.0 4 votes vote down vote up
def _matches(self, markup, match_against):
        # print u"Matching %s against %s" % (markup, match_against)
        result = False
        if isinstance(markup, list) or isinstance(markup, tuple):
            # This should only happen when searching a multi-valued attribute
            # like 'class'.
            for item in markup:
                if self._matches(item, match_against):
                    return True
            # We didn't match any particular value of the multivalue
            # attribute, but maybe we match the attribute value when
            # considered as a string.
            if self._matches(' '.join(markup), match_against):
                return True
            return False

        if match_against is True:
            # True matches any non-None value.
            return markup is not None

        if isinstance(match_against, collections.Callable):
            return match_against(markup)

        # Custom callables take the tag as an argument, but all
        # other ways of matching match the tag name as a string.
        if isinstance(markup, Tag):
            markup = markup.name

        # Ensure that `markup` is either a Unicode string, or None.
        markup = self._normalize_search_value(markup)

        if markup is None:
            # None matches None, False, an empty string, an empty list, and so on.
            return not match_against

        if isinstance(match_against, unicode):
            # Exact string match
            return markup == match_against

        if hasattr(match_against, 'match'):
            # Regexp match
            return match_against.search(markup)

        if hasattr(match_against, '__iter__'):
            # The markup must be an exact match against something
            # in the iterable.
            return markup in match_against 
Example 78
Project: analyzer-website   Author: santiagolizardo   File: element.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def _matches(self, markup, match_against):
        # print u"Matching %s against %s" % (markup, match_against)
        result = False
        if isinstance(markup, list) or isinstance(markup, tuple):
            # This should only happen when searching a multi-valued attribute
            # like 'class'.
            if (isinstance(match_against, unicode)
                and ' ' in match_against):
                # A bit of a special case. If they try to match "foo
                # bar" on a multivalue attribute's value, only accept
                # the literal value "foo bar"
                #
                # XXX This is going to be pretty slow because we keep
                # splitting match_against. But it shouldn't come up
                # too often.
                return (whitespace_re.split(match_against) == markup)
            else:
                for item in markup:
                    if self._matches(item, match_against):
                        return True
                return False

        if match_against is True:
            # True matches any non-None value.
            return markup is not None

        if isinstance(match_against, collections.Callable):
            return match_against(markup)

        # Custom callables take the tag as an argument, but all
        # other ways of matching match the tag name as a string.
        if isinstance(markup, Tag):
            markup = markup.name

        # Ensure that `markup` is either a Unicode string, or None.
        markup = self._normalize_search_value(markup)

        if markup is None:
            # None matches None, False, an empty string, an empty list, and so on.
            return not match_against

        if isinstance(match_against, unicode):
            # Exact string match
            return markup == match_against

        if hasattr(match_against, 'match'):
            # Regexp match
            return match_against.search(markup)

        if hasattr(match_against, '__iter__'):
            # The markup must be an exact match against something
            # in the iterable.
            return markup in match_against 
Example 79
Project: LaserTOF   Author: kyleuckert   File: decorators.py    MIT License 4 votes vote down vote up
def knownfailureif(fail_condition, msg=None):
    """
    Make function raise KnownFailureException exception if given condition is true.

    If the condition is a callable, it is used at runtime to dynamically
    make the decision. This is useful for tests that may require costly
    imports, to delay the cost until the test suite is actually executed.

    Parameters
    ----------
    fail_condition : bool or callable
        Flag to determine whether to mark the decorated test as a known
        failure (if True) or not (if False).
    msg : str, optional
        Message to give on raising a KnownFailureException exception.
        Default is None.

    Returns
    -------
    decorator : function
        Decorator, which, when applied to a function, causes
        KnownFailureException to be raised when `fail_condition` is True,
        and the function to be called normally otherwise.

    Notes
    -----
    The decorator itself is decorated with the ``nose.tools.make_decorator``
    function in order to transmit function name, and various other metadata.

    """
    if msg is None:
        msg = 'Test skipped due to known failure'

    # Allow for both boolean or callable known failure conditions.
    if isinstance(fail_condition, collections.Callable):
        fail_val = lambda: fail_condition()
    else:
        fail_val = lambda: fail_condition

    def knownfail_decorator(f):
        # Local import to avoid a hard nose dependency and only incur the
        # import time overhead at actual test-time.
        import nose
        from .noseclasses import KnownFailureException

        def knownfailer(*args, **kwargs):
            if fail_val():
                raise KnownFailureException(msg)
            else:
                return f(*args, **kwargs)
        return nose.tools.make_decorator(f)(knownfailer)

    return knownfail_decorator 
Example 80
Project: LaserTOF   Author: kyleuckert   File: decorators.py    MIT License 4 votes vote down vote up
def deprecated(conditional=True):
    """
    Filter deprecation warnings while running the test suite.

    This decorator can be used to filter DeprecationWarning's, to avoid
    printing them during the test suite run, while checking that the test
    actually raises a DeprecationWarning.

    Parameters
    ----------
    conditional : bool or callable, optional
        Flag to determine whether to mark test as deprecated or not. If the
        condition is a callable, it is used at runtime to dynamically make the
        decision. Default is True.

    Returns
    -------
    decorator : function
        The `deprecated` decorator itself.

    Notes
    -----
    .. versionadded:: 1.4.0

    """
    def deprecate_decorator(f):
        # Local import to avoid a hard nose dependency and only incur the
        # import time overhead at actual test-time.
        import nose

        def _deprecated_imp(*args, **kwargs):
            # Poor man's replacement for the with statement
            with assert_warns(DeprecationWarning):
                f(*args, **kwargs)

        if isinstance(conditional, collections.Callable):
            cond = conditional()
        else:
            cond = conditional
        if cond:
            return nose.tools.make_decorator(f)(_deprecated_imp)
        else:
            return f
    return deprecate_decorator