Example #1
0
 def verbose(self):
     with capture_output() as (stdout, stderr):
         namedtuple('foo', 'spam eggs', verbose=True)
     assert not stderr.getvalue()
     namespace = {}
     exec stdout.getvalue() in namespace
     Assert('foo').in_(namespace)
     Assert(namespace['foo'].__name__) == 'foo'
     Assert(namespace['foo']._fields) == ('spam', 'eggs')
Example #2
0
 def verbose(self):
     with capture_output() as (stdout, stderr):
         namedtuple('foo', 'spam eggs', verbose=True)
     assert not stderr.getvalue()
     namespace = {}
     exec stdout.getvalue() in namespace
     Assert('foo').in_(namespace)
     Assert(namespace['foo'].__name__) == 'foo'
     Assert(namespace['foo']._fields) == ('spam', 'eggs')
Example #3
0
 def _replace(self):
     nt = namedtuple('foo', ['spam', 'eggs'])
     t = nt(1, 2)
     Assert(t._replace(spam=3)) == (3, 2)
     Assert(t._replace(eggs=4)) == (1, 4)
     with Assert.raises(ValueError):
         t._replace(foo=1)
Example #4
0
 def _replace(self):
     nt = namedtuple('foo', ['spam', 'eggs'])
     t = nt(1, 2)
     Assert(t._replace(spam=3)) == (3, 2)
     Assert(t._replace(eggs=4)) == (1, 4)
     with Assert.raises(ValueError):
         t._replace(foo=1)
Example #5
0
    def fieldnames(self):
        with Assert.raises(ValueError):
            nt = namedtuple('foo', ['foo', 'bar', 'def'])

        with Assert.raises(ValueError):
            nt = namedtuple('foo', ['foo', 'bar', 'foo'])

        nt = namedtuple('foo', ['spam', 'eggs'])
        Assert(nt._fields) == ('spam', 'eggs')

        nt = namedtuple('foo', ['foo', 'bar', 'def'], rename=True)
        Assert(nt._fields) == ('foo', 'bar', '_1')
        Assert(nt(1, 2, 3)._1) == 3

        nt = namedtuple('foo', ['foo', 'bar', 'foo'], rename=True)
        Assert(nt._fields) == ('foo', 'bar', '_1')
        Assert(nt(1, 2, 3)._1) == 3
Example #6
0
    def fieldnames(self):
        with Assert.raises(ValueError):
            nt = namedtuple('foo', ['foo', 'bar', 'def'])

        with Assert.raises(ValueError):
            nt = namedtuple('foo', ['foo', 'bar', 'foo'])

        nt = namedtuple('foo', ['spam', 'eggs'])
        Assert(nt._fields) == ('spam', 'eggs')

        nt = namedtuple('foo', ['foo', 'bar', 'def'], rename=True)
        Assert(nt._fields) == ('foo', 'bar', '_1')
        Assert(nt(1, 2, 3)._1) == 3

        nt = namedtuple('foo', ['foo', 'bar', 'foo'], rename=True)
        Assert(nt._fields) == ('foo', 'bar', '_1')
        Assert(nt(1, 2, 3)._1) == 3
Example #7
0
 def _make(self):
     nt = namedtuple('foo', ['spam', 'eggs'])
     Assert(nt._make((1, 2))) == (1, 2)
     with Assert.raises(TypeError):
         nt._make((1, 2, 3))
Example #8
0
 def repr(self):
     nt = namedtuple('foo', ['spam', 'eggs'])
     Assert(nt(1, 2)) == (1, 2)
     Assert(repr(nt(1, 2))) == 'foo(spam=1, eggs=2)'
Example #9
0
 def renaming(self):
     nt = namedtuple('foo', ['foo', 'foo', 'foo'], rename=True)
     t = nt(1, 2, 3)
     Assert(t.foo) == 1
     Assert(t._1) == 2
     Assert(t._2) == 3
Example #10
0
 def typename(self):
     nt = namedtuple('foo', [])
     Assert(nt.__name__) == 'foo'
     with Assert.raises(ValueError):
         namedtuple('def', [])
Example #11
0
 def string_field_names(self):
     nt = namedtuple('foo', 'foo bar')
     Assert(nt._fields) == ('foo', 'bar')
     nt = namedtuple('foo', 'foo,bar')
     Assert(nt._fields) == ('foo', 'bar')
Example #12
0
    def docstring(self):
        nt = namedtuple('foo', 'foo bar')
        Assert(nt.__doc__) == 'foo(foo, bar)'

        nt = namedtuple('foo', 'foo bar', doc='hello user')
        Assert(nt.__doc__) == 'hello user'
Example #13
0
 def string_field_names(self):
     nt = namedtuple('foo', 'foo bar')
     Assert(nt._fields) == ('foo', 'bar')
     nt = namedtuple('foo', 'foo,bar')
     Assert(nt._fields) == ('foo', 'bar')
Example #14
0
 def typename(self):
     nt = namedtuple('foo', [])
     Assert(nt.__name__) == 'foo'
     with Assert.raises(ValueError):
         namedtuple('def', [])
Example #15
0
 def _asdict(self):
     nt = namedtuple('foo', ['spam', 'eggs'])
     Assert(nt(1, 2)._asdict()) == {'spam': 1, 'eggs': 2}
Example #16
0
 def _asdict(self):
     nt = namedtuple('foo', ['spam', 'eggs'])
     Assert(nt(1, 2)._asdict()) == {'spam': 1, 'eggs': 2}
Example #17
0
 def _make(self):
     nt = namedtuple('foo', ['spam', 'eggs'])
     Assert(nt._make((1, 2))) == (1, 2)
     with Assert.raises(TypeError):
         nt._make((1, 2, 3))
Example #18
0
 def repr(self):
     nt = namedtuple('foo', ['spam', 'eggs'])
     Assert(nt(1, 2)) == (1, 2)
     Assert(repr(nt(1, 2))) == 'foo(spam=1, eggs=2)'
Example #19
0
 def renaming(self):
     nt = namedtuple('foo', ['foo', 'foo', 'foo'], rename=True)
     t = nt(1, 2, 3)
     Assert(t.foo) == 1
     Assert(t._1) == 2
     Assert(t._2) == 3
Example #20
0
    'yellow',
    'blue',
    'purple',
    'teal',
    'white'
]
for i, name in enumerate(_colour_names):
    TEXT_COLOURS[name] = _ansi_sequence % str(i + 30)
    BACKGROUND_COLOURS[name] = _ansi_sequence % (i + 40)


Dimensions = namedtuple('Dimensions', ['height', 'width'], doc="""
    A namedtuple representing the dimensions of a terminal.

    :param height:
        The height of the terminal.

    :param width:
        The width of the terminal.
""")



class TerminalWriter(object):
    """
    This is a helper for dealing with output to a terminal.

    :param stream:
        The stream to which the output is written, per default `sys.stdout`.

    :param fallback_encoding:
Example #21
0
                                                        '04'), ('blink',
                                                                '05')])
TEXT_COLOURS = {'reset': _ansi_sequence % '39'}
BACKGROUND_COLOURS = {'reset': _ansi_sequence % '49'}
_colour_names = [
    'black', 'red', 'green', 'yellow', 'blue', 'purple', 'teal', 'white'
]
for i, name in enumerate(_colour_names):
    TEXT_COLOURS[name] = _ansi_sequence % str(i + 30)
    BACKGROUND_COLOURS[name] = _ansi_sequence % (i + 40)

Dimensions = namedtuple('Dimensions', ['height', 'width'],
                        doc="""
    A namedtuple representing the dimensions of a terminal.

    :param height:
        The height of the terminal.

    :param width:
        The width of the terminal.
""")


class TerminalWriter(object):
    """
    This is a helper for dealing with output to a terminal.

    :param stream:
        The stream to which the output is written, per default `sys.stdout`.

    :param fallback_encoding:
        The encoding used if `stream` doesn't provide one.
Example #22
0
class Signature(
        namedtuple('SignatureBase',
                   ['positionals', 'kwparams', 'varargs', 'varkwargs'])):
    """
    A named tuple representing a function signature.

    :param positionals:
       A list of required positional parameters.

    :param kwparams:
       A list containing the keyword arguments, each as a tuple containing the
       name and default value, in order of their appearance in the function
       definition.

    :param varargs:
       The name used for arbitrary positional arguments or `None`.

    :param varkwargs:
       The name used for arbitary keyword arguments or `None`.

    .. warning::
       The size of :class:`Signature` tuples may change in the future to
       accommodate additional information like annotations. Therefore you
       should not rely on it.

    .. versionadded:: 0.5
    """
    @classmethod
    def from_function(cls, func):
        """
        Constructs a :class:`Signature` from the given function or method.
        """
        func = getattr(func, 'im_func', func)
        params, varargs, varkwargs, defaults = getargspec(func)
        defaults = [] if defaults is None else defaults
        return cls(
            params[:0 if len(defaults) ==
                   len(params) else -len(defaults) or len(params)],
            zip(params[-len(defaults):], defaults), varargs, varkwargs)

    def bind_arguments(self, args=(), kwargs=None):
        """
        Returns a dictionary with the names of the parameters as keys with
        their arguments as values.

        Raises a :exc:`ValueError` if there are too many `args` and/or `kwargs`
        that are missing or repeated.
        """
        kwargs = {} if kwargs is None else kwargs

        required = set(self.positionals)
        overwritable = set(name for name, default in self.kwparams)
        settable = required | overwritable

        positional_count = len(self.positionals)
        kwparam_count = len(self.kwparams)

        result = dict(self.kwparams, **dict(zip(self.positionals, args)))

        remaining = args[positional_count:]
        for (param, _), arg in zip(self.kwparams, remaining):
            result[param] = arg
            overwritable.discard(param)
        if len(remaining) > kwparam_count:
            if self.varargs is None:
                raise ValueError(
                    'expected at most %d positional arguments, got %d' %
                    (positional_count + kwparam_count, len(args)))
            else:
                result[self.varargs] = tuple(remaining[kwparam_count:])

        remaining = {}
        unexpected = []
        for key, value in kwargs.iteritems():
            if key in result and key not in overwritable:
                raise ValueError("got multiple values for '%s'" % key)
            elif key in settable:
                result[key] = value
            elif self.varkwargs:
                result_kwargs = result.setdefault(self.varkwargs, {})
                result_kwargs[key] = value
            else:
                unexpected.append(key)
        if len(unexpected) == 1:
            raise ValueError("got unexpected keyword argument '%s'" %
                             unexpected[0])
        elif len(unexpected) == 2:
            raise ValueError("got unexpected keyword arguments '%s' and '%s'" %
                             tuple(unexpected))
        elif unexpected:
            raise ValueError(
                "got unexpected keyword arguments %s and '%s'" %
                (', '.join("'%s'" % arg
                           for arg in unexpected[:-1]), unexpected[-1]))

        if set(result) < set(self.positionals):
            missing = set(result) ^ set(self.positionals)
            if len(missing) == 1:
                raise ValueError("'%s' is missing" % missing.pop())
            elif len(missing) == 2:
                raise ValueError("'%s' and '%s' are missing" % tuple(missing))
            else:
                missing = tuple(missing)
                raise ValueError(
                    "%s and '%s' are missing" %
                    (', '.join("'%s'" % name
                               for name in missing[:-1]), missing[-1]))
        if self.varargs:
            result.setdefault(self.varargs, ())
        if self.varkwargs:
            result.setdefault(self.varkwargs, {})
        return result
Example #23
0
    def docstring(self):
        nt = namedtuple('foo', 'foo bar')
        Assert(nt.__doc__) == 'foo(foo, bar)'

        nt = namedtuple('foo', 'foo bar', doc='hello user')
        Assert(nt.__doc__) == 'hello user'