Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 24fed12

Browse files
committed
Add pretty-printing for types.SimpleNamespace
1 parent a5a8218 commit 24fed12

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

IPython/lib/pretty.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -648,6 +648,22 @@ def _re_pattern_pprint(obj, p, cycle):
648648
p.text(')')
649649

650650

651+
def _types_simplenamespace_pprint(obj, p, cycle):
652+
"""The pprint function for types.SimpleNamespace."""
653+
name = 'namespace'
654+
with p.group(len(name) + 1, name + '(', ')'):
655+
if cycle:
656+
p.text('...')
657+
else:
658+
for idx, (attr, value) in enumerate(obj.__dict__.items()):
659+
if idx:
660+
p.text(',')
661+
p.breakable()
662+
attr_kwarg = '{}='.format(attr)
663+
with p.group(len(attr_kwarg), attr_kwarg):
664+
p.pretty(value)
665+
666+
651667
def _type_pprint(obj, p, cycle):
652668
"""The pprint for classes and types."""
653669
# Heap allocated types might not have the module attribute,
@@ -741,6 +757,7 @@ def _exception_pprint(obj, p, cycle):
741757
types.FunctionType: _function_pprint,
742758
types.BuiltinFunctionType: _function_pprint,
743759
types.MethodType: _repr_pprint,
760+
types.SimpleNamespace: _types_simplenamespace_pprint,
744761
datetime.datetime: _repr_pprint,
745762
datetime.timedelta: _repr_pprint,
746763
_exception_base: _exception_pprint

IPython/lib/tests/test_pretty.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,26 @@ def test_mappingproxy():
407407
nt.assert_equal(pretty.pretty(obj), expected)
408408

409409

410+
def test_simplenamespace():
411+
SN = types.SimpleNamespace
412+
413+
sn_recursive = SN()
414+
sn_recursive.first = sn_recursive
415+
sn_recursive.second = sn_recursive
416+
cases = [
417+
(SN(), "namespace()"),
418+
(SN(x=SN()), "namespace(x=namespace())"),
419+
(SN(a_long_name=[SN(s=string.ascii_lowercase)]*3, a_short_name=None),
420+
"namespace(a_long_name=[namespace(s='abcdefghijklmnopqrstuvwxyz'),\n"
421+
" namespace(s='abcdefghijklmnopqrstuvwxyz'),\n"
422+
" namespace(s='abcdefghijklmnopqrstuvwxyz')],\n"
423+
" a_short_name=None)"),
424+
(sn_recursive, "namespace(first=namespace(...), second=namespace(...))"),
425+
]
426+
for obj, expected in cases:
427+
nt.assert_equal(pretty.pretty(obj), expected)
428+
429+
410430
def test_pretty_environ():
411431
dict_repr = pretty.pretty(dict(os.environ))
412432
# reindent to align with 'environ' prefix

0 commit comments

Comments
 (0)