Question

I'm working with an external (public domain) library that shows a tilemap on the screen. I'm trying to avoid using long chains of if...then...elif for input handing by using a dict of lambda statements that will adjust the viewport appropriately given the key pressed (as the key to the dict) and the current x, y position of the viewport.

The lambdas return the modified x and y coordinates in a tuple, but the function that sets the viewport (which I realize really ought to be handled with the use of @property, but the code already exists and would be rather painful to re-structure) takes its parameters as a separate x and y as integers.

I could make it accept a tuple by inserting the following near the top of the function:

if isinstance(fx,tuple):
    fx, fy = fx

but if we want to be super Pythonic to spite the original library developers, this won't do- the duck typing paradigm suggests that any object that can contain an x and a y value should be acceptable.

How would I implement this?

Was it helpful?

Solution

Use *params calls to the viewport function instead:

coordinates = lambda_mapping[key](argument)
viewport_set(*coordinates)

This applies the coordinates tuple as separate arguments to the viewport_set() function.

Demo:

>>> def foo(x, y):
...     print(x, y)
... 
>>> coordinates = (42, 38)
>>> foo(*coordinates)
42 38

Now you don't have to adjust the viewport function to take tuples as well as separate arguments.

The other alternative is to make the second coordinate a keyword argument:

def viewport_set(x, y=None):
    if y is None:
        # assume x is a sequence of two coordinates instead
        x, y = x
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top