I am trying to do something like this in python:
def foo(x, y):
# do something at position (x, y)
def foo(pos):
foo(pos.x, pos.y)
So I want to call a different version of foo depending on the number of parameters I provide. This of course doesn't work because I redefined foo
.
What would be the most elegant way of achieving this? I would prefer not to use named parameters.
Usually you'd either define two different functions, or do something like:
The option to define two different functions seems unwieldy if you're used to languages that have overloading, but if you're used to languages like Python or C that don't, then it's just what you do. The main problem with the above code in Python is that it's a bit awkward to document the first parameter, it doesn't mean the same in the two cases.
Another option is to only define the version of
foo
that takes a pos, but also supply a type for users:Then anyone who would have written
foo(x,y)
can instead writefoo(Pos(x,y))
. Naturally there's a slight performance cost, since an object has to be created.