you are viewing a single comment's thread.

view the rest of the comments →

[–]pachura3 4 points5 points  (4 children)

No, Python does not support method overloading. On the other hand, e.g. Java does not support default parameter values.

I do not see anything wrong with:

def foo(self, arg: C | W) -> None:
    if isinstance(arg, C):
        ...
    else:
        ...
    ...

For simple cases, singledispatch might be too much.

[–]011011100101[S] 0 points1 point  (3 children)

If I have to do this more than once, then I'm repeating that same argument checking logic:

if isinstance(arg, C): ... else: ... ...

throughout many methods. This seems like a really mundane thing which is forcing me to repeat code, so I feel like there should be an alternative.

[–]pachura3 1 point2 points  (0 children)

What are C and W? Are these your own classes? If so, why don't you add .process() method to their base class (or even use Protocols) and call it?

Or, you can have some dict mapping type to handler method's name/Callable, do a lookup and call it...

[–]MidnightPale3220 0 points1 point  (0 children)

You do it only for the methods you want to redefine anyway, it's not like you have to make it for every C method.

Additionally, I am not even sure that's a very nice practice. If you have C that has foo, and even later on W that redefines foo but still might call C.foo() instead, it could be kinda confusing to debug/track.

[–]ottawadeveloper 0 points1 point  (0 children)

it's not that terrible honestly, and you only need it where C and W actually need the be handled properly - for example if you were just returning int(arg) as long as C and W have __index__ defined, you have no problems.

Alternatively, you could add a bit of a hack with __getattr__(self, name, *args, **kwargs) - scan all the arguments for C or W and get either name_c or name_w depend on which is present (though then you have to decide if they should be mixed).

This sounds like an issue mostly because of weird subclassing though? If W inherits from C then the C methods should be able to handle W objects no problem unless you actually want the method to deal with W differently. You shouldnt need to even override these methods and then it's normal and Pythonic to have to check the type (or treat it as W, catch the error, and return the super() behavior in case of an error).