3 ms·
> In Python, whether 2 or 3, as a developer you do not have the luxury of informed reasoning whether something is bytes or a string, because your functions' inp
by dehrmann 6y ago
> In Python, whether 2 or 3, as a developer you do not have the luxury of informed reasoning whether something is bytes or a string, because your functions' input parameters can be either.
I guess they can be, but the code might also work on an int tuple, even though the operation doesn't make any sense. Here's a case where duck typing does something, but it doesn't make sense.
import functools
def sum2(vals):
return functools.reduce(lambda a, b: a + b, vals)
Python's built-in sum won't work on strings or lists of strings (so much for saying the language is duck typed), but this will. It's also weird because addition is associative, but not with strings, so changing a+b to b+a changes the behavior and gives you a very cute answer to the "reverse a string" algorithm:
reverse = sum2
In practice, every legitimate use I've seen for duck typing might as well use what would be an interface in Java. I see duck typing as interfaces without the formality of declaring them. If you violate the implicit contract, funny things happen, and this is why Typescript got so popular and Python added type annotations.