Function Overloading

``` @overload def process(self, x, y, z, _method=1): ...

@overload def process(self, node, _method=2): ...

def process(self, x=None, y=None, z=None, node=None, *, _method): if _method == 1: print(f"{x=} {y=} {z=}") if _method == 2: print(f"{node=}") # or a match (switch-case) on _method ```

I have a function that could either process a node, or convert coordinates to a node which can then be processed. Is the code above a good way of doing it, or is there a better method I am not aware of?

To me, the syntax / layout and logic makes sense; but if there is a better / more pythonic / higher performance / ... solution I'd like to hear about it so I can do some research and testing. This is my first real application of function overloading so I'm still getting my head around it.

I could also put def xxx(self, *, parameters) to make sure the correct parameters are given because they have to be passed by keyword only? I'm not sure if it makes a difference.

Alternatively, I was thinking I could just have process_coordinate(x, y, z) and process_node(node) where PC does the conversion and passes the node to PN which does the actual processing. Or I can use PN directly if I already have a node.

I'd like to hear anyone's thoughts and feedback. TIA

4 comments · 67% upvoted · other discussions

comments

TangibleLight

I would prefer separate functions. Extra logic like this parsing parameters usually makes things harder to understand in the long run, when your one function might do one thing or the other with mutually exclusive arguments.

Especially if this is a case where you can decompose the function into two functions where one just calls the other.

InvaderToast348 [OP]

I have split it into the 2 functions as mentioned and it is working great! Two separate functions are a lot simpler in both logic and syntax, with less room for errors; I suppose it was the obvious choice but I wanted a second opinion. Thank you.