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

Diapolo10

typing.overload is a tool for type annotations, not a generic enabler of function overloading (which is not a feature Python really supports anyway). So the way you're using it here is wrong.

In this case I'd split this into separate functions as I don't see the value of keeping them combined like this.

InvaderToast348 [OP]

Thank you