Skip to content

Commit

Permalink
made bbrepr recursive using reprlib
Browse files Browse the repository at this point in the history
  • Loading branch information
Kurt Rose committed Jul 8, 2020
1 parent 8d7b59e commit 25e7bf6
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
28 changes: 19 additions & 9 deletions glom/core.py
Expand Up @@ -40,10 +40,12 @@
if PY2:
_AbstractIterableBase = object
from .chainmap_backport import ChainMap
import repr as reprlib
else:
basestring = str
_AbstractIterableBase = ABCMeta('_AbstractIterableBase', (object,), {})
from collections import ChainMap
import reprlib

GLOM_DEBUG = os.getenv('GLOM_DEBUG', '').strip().lower()
GLOM_DEBUG = False if (GLOM_DEBUG in ('', '0', 'false')) else True
Expand Down Expand Up @@ -400,14 +402,25 @@ def get_message(self):
_BUILTIN_ID_NAME_MAP = dict([(id(v), k)
for k, v in __builtins__.items()])

def bbrepr(obj):

class _BBRepr(reprlib.Repr):
"""A better repr for builtins, when the built-in repr isn't
roundtrippable.
"""
ret = repr(obj)
if not ret.startswith('<'):
return ret
return _BUILTIN_ID_NAME_MAP.get(id(obj), ret)
def __init__(self):
super(_BBRepr, self).__init__()
# turn up all the length limits very high
for name in self.__dict__:
setattr(self, name, 1024)

def repr1(self, x, maxlevel):
ret = super(_BBRepr, self).repr1(x, maxlevel)
if not ret.startswith('<'):
return ret
return _BUILTIN_ID_NAME_MAP.get(id(x), ret)


bbrepr = _BBRepr().repr


class _BBReprFormatter(string.Formatter):
Expand All @@ -421,10 +434,7 @@ def convert_field(self, value, conversion):
return super(_BBReprFormatter, self).convert_field(value, conversion)


_BB_REPR_FORMATTER = _BBReprFormatter()


bbformat = _BB_REPR_FORMATTER.format
bbformat = _BBReprFormatter().format


# TODO: push this back up to boltons with repr kwarg
Expand Down
6 changes: 5 additions & 1 deletion glom/test/test_basic.py
Expand Up @@ -8,7 +8,7 @@
from glom import Auto, Fill, Iter

import glom.core as glom_core
from glom.core import UP, ROOT, Let, bbformat
from glom.core import UP, ROOT, Let, bbformat, bbrepr

from glom import OMIT # backwards compat

Expand Down Expand Up @@ -463,3 +463,7 @@ def test_api_repr():

def test_bbformat():
assert bbformat("{0.__name__}", int) == "int"


def test_bbrepr():
assert bbrepr({str: int}) == "{str: int}"

0 comments on commit 25e7bf6

Please sign in to comment.