Exemple #1
0
    def test_knotted(self):
        # Verify .isrecursive() and .isreadable() w/ recursion
        # Tie a knot.
        self.b[67] = self.a
        # Messy dict.
        self.d = {}
        self.d[0] = self.d[1] = self.d[2] = self.d

        verify = self.assertTrue
        pp = pprint.PrettyPrinter()

        for icky in self.a, self.b, self.d, (self.d, self.d):
            verify(pprint.isrecursive(icky), "expected isrecursive")
            verify(not pprint.isreadable(icky),  "expected not isreadable")
            verify(pp.isrecursive(icky), "expected isrecursive")
            verify(not pp.isreadable(icky),  "expected not isreadable")

        # Break the cycles.
        self.d.clear()
        del self.a[:]
        del self.b[:]

        for safe in self.a, self.b, self.d, (self.d, self.d):
            # module-level convenience functions
            verify(not pprint.isrecursive(safe),
                   "expected not isrecursive for %r" % (safe,))
            verify(pprint.isreadable(safe),
                   "expected isreadable for %r" % (safe,))
            # PrettyPrinter methods
            verify(not pp.isrecursive(safe),
                   "expected not isrecursive for %r" % (safe,))
            verify(pp.isreadable(safe),
                   "expected isreadable for %r" % (safe,))
 def test_unreadable(self):
     """Not recursive but not readable anyway."""
     verify = self.assert_
     for unreadable in type(3), pprint, pprint.isrecursive:
         verify(not pprint.isrecursive(unreadable),
                "expected not isrecursive for " + `unreadable`)
         verify(not pprint.isreadable(unreadable),
                "expected not isreadable for " + `unreadable`)
 def test_basic(self):
     """Verify .isrecursive() and .isreadable() w/o recursion."""
     verify = self.assert_
     for safe in (2, 2.0, 2j, "abc", [3], (2,2), {3: 3}, uni("yaddayadda"),
                  self.a, self.b):
         verify(not pprint.isrecursive(safe),
                "expected not isrecursive for " + `safe`)
         verify(pprint.isreadable(safe),
                "expected isreadable for " + `safe`)
Exemple #4
0
 def test_basic(self):
     # Verify .isrecursive() and .isreadable() w/o recursion
     pp = pprint.PrettyPrinter()
     for safe in (2, 2.0, 2j, "abc", [3], (2, 2), {3: 3}, "yaddayadda", self.a, self.b):
         # module-level convenience functions
         self.assertFalse(pprint.isrecursive(safe), "expected not isrecursive for %r" % (safe,))
         self.assertTrue(pprint.isreadable(safe), "expected isreadable for %r" % (safe,))
         # PrettyPrinter methods
         self.assertFalse(pp.isrecursive(safe), "expected not isrecursive for %r" % (safe,))
         self.assertTrue(pp.isreadable(safe), "expected isreadable for %r" % (safe,))
Exemple #5
0
 def test_unreadable(self):
     # Not recursive but not readable anyway
     pp = pprint.PrettyPrinter()
     for unreadable in type(3), pprint, pprint.isrecursive:
         # module-level convenience functions
         self.assertFalse(pprint.isrecursive(unreadable), "expected not isrecursive for %r" % (unreadable,))
         self.assertFalse(pprint.isreadable(unreadable), "expected not isreadable for %r" % (unreadable,))
         # PrettyPrinter methods
         self.assertFalse(pp.isrecursive(unreadable), "expected not isrecursive for %r" % (unreadable,))
         self.assertFalse(pp.isreadable(unreadable), "expected not isreadable for %r" % (unreadable,))
    def test_knotted(self):
        """Verify .isrecursive() and .isreadable() w/ recursion."""
        # Tie a knot.
        self.b[67] = self.a
        # Messy dict.
        self.d = {}
        self.d[0] = self.d[1] = self.d[2] = self.d

        verify = self.assert_

        for icky in self.a, self.b, self.d, (self.d, self.d):
            verify(pprint.isrecursive(icky), "expected isrecursive")
            verify(not pprint.isreadable(icky),  "expected not isreadable")

        # Break the cycles.
        self.d.clear()
        del self.a[:]
        del self.b[:]

        for safe in self.a, self.b, self.d, (self.d, self.d):
            verify(not pprint.isrecursive(safe),
                   "expected not isrecursive for " + `safe`)
            verify(pprint.isreadable(safe),
                   "expected isreadable for " + `safe`)
 def test_unreadable(self):
     # Not recursive but not readable anyway
     verify = self.assert_
     pp = pprint.PrettyPrinter()
     for unreadable in type(3), pprint, pprint.isrecursive:
         # module-level convenience functions
         verify(not pprint.isrecursive(unreadable),
                "expected not isrecursive for " + `unreadable`)
         verify(not pprint.isreadable(unreadable),
                "expected not isreadable for " + `unreadable`)
         # PrettyPrinter methods
         verify(not pp.isrecursive(unreadable),
                "expected not isrecursive for " + `unreadable`)
         verify(not pp.isreadable(unreadable),
                "expected not isreadable for " + `unreadable`)
Exemple #8
0
 def test_basic(self):
     # Verify .isrecursive() and .isreadable() w/o recursion
     pp = pprint.PrettyPrinter()
     for safe in (2, 2.0, 2j, "abc", [3], (2, 2), {
             3: 3
     }, uni("yaddayadda"), self.a, self.b):
         # module-level convenience functions
         self.assertFalse(pprint.isrecursive(safe),
                          "expected not isrecursive for %r" % (safe, ))
         self.assertTrue(pprint.isreadable(safe),
                         "expected isreadable for %r" % (safe, ))
         # PrettyPrinter methods
         self.assertFalse(pp.isrecursive(safe),
                          "expected not isrecursive for %r" % (safe, ))
         self.assertTrue(pp.isreadable(safe),
                         "expected isreadable for %r" % (safe, ))
Exemple #9
0
 def test_unreadable(self):
     # Not recursive but not readable anyway
     pp = pprint.PrettyPrinter()
     for unreadable in type(3), pprint, pprint.isrecursive:
         # module-level convenience functions
         self.assertFalse(
             pprint.isrecursive(unreadable),
             "expected not isrecursive for %r" % (unreadable, ))
         self.assertFalse(pprint.isreadable(unreadable),
                          "expected not isreadable for %r" % (unreadable, ))
         # PrettyPrinter methods
         self.assertFalse(
             pp.isrecursive(unreadable),
             "expected not isrecursive for %r" % (unreadable, ))
         self.assertFalse(pp.isreadable(unreadable),
                          "expected not isreadable for %r" % (unreadable, ))
 def test_basic(self):
     # Verify .isrecursive() and .isreadable() w/o recursion
     verify = self.assert_
     pp = pprint.PrettyPrinter()
     for safe in (2, 2.0, 2j, "abc", [3], (2,2), {3: 3}, uni("yaddayadda"),
                  self.a, self.b):
         # module-level convenience functions
         verify(not pprint.isrecursive(safe),
                "expected not isrecursive for " + `safe`)
         verify(pprint.isreadable(safe),
                "expected isreadable for " + `safe`)
         # PrettyPrinter methods
         verify(not pp.isrecursive(safe),
                "expected not isrecursive for " + `safe`)
         verify(pp.isreadable(safe),
                "expected isreadable for " + `safe`)
Exemple #11
0
def _itree(obj, formatter, subscription, prefix="", last=False, level=0, depth=0):
    formatter.level = level
    sprout = level > 0
    children = []
    objid = id(obj)
    recursive = isrecursive(obj)
    recursive_ids = _recursive_ids.get()
    sprout_repr = ': ' if sprout else ''
    newlevel = '    ' if last else formatter.EDGE
    newline_prefix = f"{prefix}{newlevel}"
    newprefix = f"{prefix}{formatter.BRANCH_LAST if last else formatter.BRANCH_NEXT}" if sprout else ""
    subscription_repr = f'{newprefix}{_newline_repr(f"{subscription}", newline_prefix)}'
    if recursive and objid in recursive_ids:
        item_repr = f"{sprout_repr}<Recursion on {type(obj).__name__} with id={objid}>"
    elif isinstance(obj, (str, bytes)):
        # Indent new lines with a prefix so that a string like "new\nline" adjusts to:
        #      ...
        #      |- 42: new
        #      |      line
        #      ...
        # for this, calculate how many characters each new line should have for padding
        prefix_len = len(prefix)  # how much we have to copy before subscription string
        last_line = subscription_repr.expandtabs().splitlines()[-1]
        newline_padding = len(last_line[prefix_len:]) + prefix_len + 2  # last 2 are ": "
        item_repr = _newline_repr(f"{sprout_repr}{obj}", f"{last_line[:prefix_len] + newlevel:<{newline_padding}}")
    elif isinstance(obj, abc.Iterable):
        # for other iterable objects, enumerate to track subscription and child count
        ismap = isinstance(obj, abc.Mapping)
        enumerateable = obj.items() if ismap else obj
        accessor = (lambda i, v: (i, *v)) if ismap else lambda i, v: (i, i, v)
        enumerated = enumerate(enumerateable)
        children.extend(accessor(*enum) for enum in enumerated)
        contents = f'items={len(children)}' if children else "empty"
        item_repr = f' {formatter.ARROW} {type(obj).__name__}[{contents}]' if formatter.annotated else ''
        if children and level == depth:
            item_repr = f"{item_repr} [...]"
            children.clear()  # avoid deeper traversal
    else:
        item_repr = f"{sprout_repr}{obj}"
    if recursive:
        recursive_ids.add(objid)

    yield f"{subscription_repr}{item_repr}"
    child_count = len(children)
    prefix += newlevel if sprout else ""  # only add level prefix starting at level 1
    for index, key, value in children:
        yield from _itree(value, formatter, key, prefix, index == (child_count - 1), level + 1, depth)
Exemple #12
0
def add_up_and_multiply(*args, **kwargs) -> (int, int):
    """
    Accept any number of positional and keyword arguments
    and return their sum and product.
    Parameters can be any number or iterable of numbers

    :param args: number or iterable of numbers
    :param kwargs: number or iterable of numbers
    :return: tuple(int, int)
    """
    arguments = list(args) + list(kwargs.values())
    if pprint.isrecursive(arguments):
        print("arguments has cycled links")
        return None
    flat_list = flatten(arguments)
    _sum = sum(flat_list)
    _mul = functools.reduce(operator.mul, filter(None, flat_list))
    return _sum, _mul
Exemple #13
0
 def isrecursive(self, object):
     return isrecursive(object)
Exemple #14
0
pp = pprint.PrettyPrinter(width=41, compact=True)
pp.pprint(stuff)

tup = ('spam', ('eggs', ('lumberjack',
                         ('knights', ('ni', ('dead', ('parrot',
                                                      ('fresh fruit', ))))))))
pp = pprint.PrettyPrinter(depth=6)
pp.pprint(tup)

print(pprint.pformat(tup, depth=6))

# pprint.pp(tup) # 3.8

pprint.pprint(tup, depth=6)

print(pprint.isreadable(tup))
print(pprint.isrecursive(tup))

print("-----------------")

import json
import pprint
from urllib.request import urlopen

with urlopen('https://pypi.org/pypi/sampleproject/json') as resp:
    project_info = json.load(resp)['info']

pprint.pprint(project_info)

pprint.pprint(project_info, depth=1, width=60)
Exemple #15
0
import pprint
print("""
pprint.pformat(object, indent=1, width=80, depth=None, *, compact=False)
    Return the formatted representation of object as a string. indent, width, depth and compact will be passed to the PrettyPrinter constructor as formatting parameters.
    Changed in version 3.4: Added the compact parameter.
pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False)
    Prints the formatted representation of object on stream, followed by a newline. If stream is None, sys.stdout is used. This may be used in the interactive interpreter instead of the print() function for inspecting values (you can even reassign print = pprint.pprint for use within a scope). indent, width, depth and compact will be passed to the PrettyPrinter constructor as formatting parameters.
    Changed in version 3.4: Added the compact parameter.
""")
import pprint
stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
stuff.insert(0, stuff)
pprint.pprint(stuff)
print("""
pprint.isreadable(object)
    Determine if the formatted representation of object is “readable,” or can be used to reconstruct the value using eval(). This always returns False for recursive objects.
""")
pprint.isreadable(stuff)
print("""
pprint.isrecursive(object)
    Determine if object requires a recursive representation.
One more support function is also defined:
pprint.saferepr(object)
    Return a string representation of object, protected against recursive data structures. If the representation of object exposes a recursive entry, the recursive reference will be represented as <Recursion on typename with id=number>. The representation is not otherwise formatted.
pprint.isrecursive(object)
    Determine if object requires a recursive representation.
One more support function is also defined:
pprint.saferepr(object)
    Return a string representation of object, protected against recursive data structures. If the representation of object exposes a recursive entry, the recursive reference will be represented as <Recursion on typename with id=number>. The representation is not otherwise formatted.
""")
pprint.saferepr(stuff)
Exemple #17
0
#! /usr/bin/env python

import pprint

stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
tup = (stuff, 'spam', ('eggs', ('lumberjack',
                                ('knights', ('ni', ('dead',
                                                    ('parrot',
                                                     ('fresh fruit', ))))))))
stuff.insert(0, tup)
a = ['aaa', 'bbb']
tt = []
tt.append(a)
tt.append(a)
print tt
pprint.pprint(tt)
print pprint.isrecursive(tt)
print pprint.pformat(tt)
print pprint.saferepr(tt)
Exemple #18
0
 def update_event(self, inp=-1):
     self.set_output_val(0, pprint.isrecursive(self.input(0)))
Exemple #19
0
import pprint