r/pythonhelp • u/AceScottieAC3 • 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
1
u/Goobyalus May 10 '23
Actually I take back my previous comment.
singledispatchworks off the type of the first argument, so ifstris valid for the first argument in both cases, it won't work for you.