Python Forum
function/method keyword argument alias
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
function/method keyword argument alias
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?

Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
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):
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:',
            return d.popitem()[1]
        return default
if __name__ == '__main__':
    putfoo('hello', position=7)
    putfoo('hello', pos=9)
    putfoo('hello', position= 11, pos=13)
Position is: 7 Position is: 9 Traceback (most recent call last): File "paillasse/", line 24, in <module> putfoo('hello', position= 11, pos=13) File "paillasse/", line 3, in putfoo pos = merge_aliases(None, position=position, pos=pos) File "paillasse/", line 15, in merge_aliases list(d.keys())) __main__.TooManyParameters: ('Only one of the following parameters can be set:', ['pos', 'position'])

Possibly Related Threads…
Thread Author Replies Views Last Post
  omitting arguments in function/method calls Skaperen 10 1,303 Nov-24-2019, 10:13 PM
Last Post: Gribouillis
  Is that possible to have a new feature: dynamic return with using function argument kouui 2 733 Aug-26-2019, 10:05 AM
Last Post: kouui

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020