Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions fire/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,9 @@ def _OneLineResult(result):
if inspect.ismodule(result):
return f'<module {result.__name__}>'

if inspectutils.IsNamedTuple(result):
return json.dumps(result._asdict(), ensure_ascii=False)

try:
# Don't force conversion to ascii.
return json.dumps(result, ensure_ascii=False)
Expand Down
7 changes: 7 additions & 0 deletions fire/core_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

"""Tests for the core module."""

import collections
from unittest import mock

from fire import core
Expand Down Expand Up @@ -137,6 +138,12 @@ def testPrintOrderedDict(self):
with self.assertOutputMatches(stdout='{}'):
core.Fire(tc.OrderedDictionary, command=['empty'])

def testPrintDictOfNamedTuples(self):
point = collections.namedtuple('Point', ['x', 'y'])
data = {'a': point(1, 2), 'b': point(3, 4)}
with self.assertOutputMatches(stdout=r'a:\s+\{"x": 1, "y": 2\}', stderr=None):
core.Fire(data, command=[])

def testPrintNamedTupleField(self):
with self.assertOutputMatches(stdout='11', stderr=None):
core.Fire(tc.NamedTuple, command=['point', 'x'])
Expand Down
3 changes: 2 additions & 1 deletion fire/value_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ def IsSimpleGroup(component):
"""
assert isinstance(component, dict)
for unused_key, value in component.items():
if not IsValue(value) and not isinstance(value, (list, dict)):
if (not IsValue(value) and not isinstance(value, (list, dict))
and not inspectutils.IsNamedTuple(value)):
return False
return True

Expand Down