I posted DWIM is consistent on Friday, 27 December, 2019

Post perl python DWIM

DWIM is consistent

Moshe Zadka has been writing a mostly excellent exploration of the Zen of Python for Opensource.com. Not sure I approve of this take on guessing, from The importance of consistency in your Python code:

What should the result of 1 + "1" be? Both "11" and 2 would be valid guesses. This expression is ambiguous: there is no single thing it can do that would not be a surprise to at least some people.

Some languages choose to guess. In JavaScript, the result is "11". In Perl, the result is 2. In C, naturally, the result is the empty string. In the face of ambiguity, JavaScript, Perl, and C all guess.

I can’t speak for the other languages, but Perl isn’t guessing. It’s adding these two values as numbers because we told it to by using the numeric + operator. If we wanted a string, we would tell Perl, by using the . concatenation operator.

Let’s fire up tinyrepl for a quick demonstration.

$ tinyrepl
re.pl$ 1 + "1"
re.pl$ 1 . "1"

Perl operators do the type casting for you. This is DWIM – “Do What I Mean” – in action. You say you want numbers? Perl gives you numbers. You say you want strings? Perl gives you strings.

Are 1 + "1" and 1 . "1" better than 1 + int("1") and str(1) + "1"? I don’t know. Perl was born for text processing. Most of its affordances make the most sense in that context.

DWIM can be surprising to those unfamiliar with this approach. But it’s not guessing.

The points about consistency and ambiguity are solid. The Zen of Python can be applied with slight modifications to all programming. Just remember that ``obvious'' is different in different languages.


Got a comment? A question? More of a comment than a question? Talk to me about this post!

Indieweb Social

Did you mention this somewhere? I'd love it if you sent me the link!

disclaimer about timing

Mentions are sent to webmention.io. I fetch the latest mentions when building the site, so I may not see your feedback right away. Especially if my site's broken, which is often the case.

Public replies and mentions might be shared on the site, but I try to do a little quality check first.

Site Links