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'1
u/Goobyalus May 09 '23
On an unrelated note, is this a function or a method?
I would avoid shadowing the builtin set.
1
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
1
u/Goobyalus May 09 '23
Probably the best way would be with functools' singledispatch
https://docs.python.org/3/library/functools.html#functools.singledispatch
2
u/sentles May 09 '23
One way is to set the default value of
texttoNone. At the start of your function, check iftext is None. If it is, settext = index, and setindexto whatever default value you use when it isn't passed.Another way is to instead not use arguments
indexandtest, but just use*args. If the length ofargsis 1, use the argument astext, else if it is 2, use them asindexandtextrespectively.I'd prefer the former, or course, since it's clearer what arguments are expected.