I think the kwargs approach is fine for when you’re reading your code. When you’re writing I think you’ll always have to consult the docs, or headers. In a strongly typed language IDE can pick up the hint but in a more dynamic language like python it can get confused.
Re:Overload functions in Python
by testuser66 on Thursday February 20, 2020 @04:50AM
(#22373902)
My bad - I meant this but didn't know how to format code so that is showed the stars
def func(*args, **kwargs)
I am in full support of actual kwargs with names, it's the wildcard ones that I don't like.
Re:Overload functions in Python
by joshuamorton on Tuesday February 18, 2020 @03:07AM
(#22354308)
by "kwargs" the usual approach is to have optional arguments ("keyword arguments") that aren't just kwargs, but are named optional arguments:
def func(args, flag=False, flag2=True)
Re:Overload functions in Python
by testuser66 on Thursday February 20, 2020 @04:48AM
(#22373887)
I fully agree that named kwargs is perfectly acceptable, but this is the version I think is horrible:
def func(*args, **kwargs)
is valid and completely ambiguous - you have no idea what it's doing unless you read the source, and track down how it branches out. IDEs are stopped dead in their tracks as they aren't going to parse the logic to figure it outAnd yes it's not the most common approach, but I have seen it enough times to despise it. This overloading approach removes the need for it so I'm all for that.
Re:Overload functions in Python
by joshuamorton on Thursday February 20, 2020 @04:57AM
(#22373934)
> This overloading approach removes the need for it so I'm all for that.
Ish, see if your IDE supports it (hint: it won't, but it will support named kwargs).
Re:Overload functions in Python
by testuser66 on Friday February 28, 2020 @02:56AM
(#22441236)
And it doesn't really need to. Consider this:
from functools import singledispatch
from typing import Union
@singledispatch
def myfunc(arg:Union[int, str]):
print("Called with something else")
@myfunc.register
def _(arg:int):
print("Called the one with int")
@myfunc.register
def _(arg:str):
print("Called the one with str")
myfunc(123)
myfunc("123")
Everything works as you'd expect, and the IDE's type hints are accurate as long as you actually put the correct type hint def myfunc(arg:Union[int, str]):
If you can get away with just a bunch of named kwargs after the arguments that is fine, but I'd take overloading over the `args, kwargs` garbage any day, even if that is the more "pythonic" way.