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
17 changes: 13 additions & 4 deletions fire/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,12 @@ def SetParseFn(fn, *arguments):
The decorated function, which now has metadata telling Fire how to perform.
"""
def _Decorator(func):
parse_fns = GetParseFns(func)
existing = GetParseFns(func)
parse_fns = {
'default': existing.get('default'),
'positional': list(existing.get('positional', [])),
'named': dict(existing.get('named', {})),
}
if not arguments:
parse_fns['default'] = fn
else:
Expand Down Expand Up @@ -66,8 +71,12 @@ def SetParseFns(*positional, **named):
The decorated function, which now has metadata telling Fire how to perform.
"""
def _Decorator(fn):
parse_fns = GetParseFns(fn)
parse_fns['positional'] = positional
existing = GetParseFns(fn)
parse_fns = {
'default': existing.get('default'),
'positional': positional if positional else tuple(existing.get('positional', ())),
'named': dict(existing.get('named', {})),
}
parse_fns['named'].update(named)
_SetMetadata(fn, FIRE_PARSE_FNS, parse_fns)
return fn
Expand All @@ -76,7 +85,7 @@ def _Decorator(fn):


def _SetMetadata(fn, attribute, value):
metadata = GetMetadata(fn)
metadata = dict(GetMetadata(fn))
metadata[attribute] = value
setattr(fn, FIRE_METADATA, metadata)

Expand Down
27 changes: 27 additions & 0 deletions fire/decorators_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

"""Tests for the decorators module."""

import functools
from fire import core
from fire import decorators
from fire import testutils
Expand Down Expand Up @@ -165,6 +166,32 @@ def testSetParseFn(self):
command=['example7', '1', '--arg2=2', '3', '4', '--kwarg=5']),
('1', '2', ('3', '4'), {'kwarg': '5'}))

def testSetParseFnsFunctoolsWraps(self):
@decorators.SetParseFns(value=int)
def original(value):
return type(value).__name__

@decorators.SetParseFns(value=str)
@functools.wraps(original)
def wrapped(value):
return original(value)

self.assertEqual(core.Fire(original, command=['01']), 'int')
self.assertEqual(core.Fire(wrapped, command=['01']), 'str')

def testSetParseFnFunctoolsWraps(self):
@decorators.SetParseFn(int, 'value')
def original(value):
return type(value).__name__

@decorators.SetParseFn(str, 'value')
@functools.wraps(original)
def wrapped(value):
return original(value)

self.assertEqual(core.Fire(original, command=['01']), 'int')
self.assertEqual(core.Fire(wrapped, command=['01']), 'str')


if __name__ == '__main__':
testutils.main()
Loading