r/pythonhelp • • May 09 '23

args/kwargs ordering and defaults.

I have a method set() which accepts the possibility of a index and text.

def set(self, index:str|int|float=None, text:str="", **kwargs):
print(index, text)

My issue is if only 1 arg is passed i want it to be set to 'text' however if 2 or more are passed then it should be set to index, text then kwargs.

example uses:

set(0, 'some text', colour='blue') #-> index=0, text='some text', kwargs{'colour':'blue'}
set('some text') #-> index=None, text='some text'
set('end', 'some text') #-> index='end', text='some text'
set(1.0, 'some text') #-> index=1.0, text='some text'
set(text='some text') #-> index=0, text='some text'
3 Upvotes

10 comments sorted by

View all comments

1

u/Goobyalus May 10 '23

Actually I take back my previous comment. singledispatch works off the type of the first argument, so if str is valid for the first argument in both cases, it won't work for you.

1

u/AceScottieAC3 May 10 '23

If its possible to change the target of singledispactch check to the text arg then i could use

from functools import singledispatch
NoneType = type(None)
@singledispatch
def test(index, text):
    print(index, text)
@test.register(str)
def _(index, text=None):
    print(index, text, 'str')
@test.register(NoneType)
def _(index, text:None=None):
    print(index, text, 'None')

1

u/Goobyalus May 10 '23

You could roll your own dispatch, but it looks to me like the builtin one explicitly uses the first positional argument's type:

https://github.com/python/cpython/blob/main/Lib/functools.py#L909