function/method keyword argument alias - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: News and Discussions (https://python-forum.io/forum-31.html) +--- Thread: function/method keyword argument alias (/thread-22874.html) |
function/method keyword argument alias - Skaperen - Dec-01-2019 is there a way to handle function/method keyword aliasing other than using **kwargs and coding the logic to handle it? for example i might have position= for a defined function/method but also want to allow pos= to be the same thing. what about multiple aliases? what if the caller uses more than one of them?putfoo(bar,position=5,pos=3) RE: function/method keyword argument alias - Gribouillis - Dec-01-2019 You can do anything in python, but this is really not pythonic def putfoo(bar, position=None, pos=None): pos = merge_aliases(None, position=position, pos=pos) print('Position is:', repr(pos)) class TooManyParameters(RuntimeError): pass def merge_aliases(default, **kwargs): d = {k: v for k, v in kwargs.items() if v is not default} if d: if len(d) > 1: raise TooManyParameters( 'Only one of the following parameters can be set:', list(d.keys())) else: return d.popitem()[1] else: return default if __name__ == '__main__': putfoo('hello', position=7) putfoo('hello', pos=9) putfoo('hello', position= 11, pos=13)
|