by hcarvalhoalves · 12y ago · 0 comments
> No problems here. The first noticible crack in the system comes after a few weeks vacation away from this code. You come back, and you want to change the starting point of the player. Will you remember which Vector2 to change?
player = Player(position=Vector2(100, 100), size=Vector2(50, 50))
The problem is not typing here, it's lack of named arguments.Both of the following would compile successfully using named arguments but one of them is semantically wrong:
Player(pos = v1, size = v2);
Player(pos = v2, size = v1);
Using a compiler's static type checking enforces correct semantics more than named arguments. Of course, this only works if the programmer creates new differentiated types so that they are no longer identical (which was the crux of the article.)
For example when you have one function returning (pos, size) and another function expecting (size, pos).
>>> from collections import namedtuple
>>> Vector2 = namedtuple('Vector2', ('x', 'y'))
>>> PlayerOptions = namedtuple('PlayerOptions', ('position', 'size'))
>>> opt = PlayerOptions(position=Vector2(100, 100), size=Vector2(50, 50))
>>> Player(**opt._asdict())
The order arguments are passed doesn't matter anymore. You can also enforce this calling convention with a constructor signature like this (in 3): >>> class Player(object):
>>> def __init__(self, *, size, position):