Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

x or y: acceptable idiom, or obfuscation?

I have to extract values from a variable that may be None, with some defaults in mind. I first wrote this code:

if self.maxTiles is None:
    maxX, maxY = 2, 2
else:
    maxX, maxY = self.maxTiles

Then I realized I could shorten it to:

maxX, maxY = self.maxTiles if self.maxTiles is not None else (2, 2)

But then I realized this might be the most succinct and easily readable:

maxX, maxY = self.maxTiles or (2, 2)

Is the latter acceptable, or too hackish?

like image 790
Claudiu Avatar asked Dec 03 '22 04:12

Claudiu


1 Answers

About, specifically,

self.maxTiles if self.maxTiles is not None else (2, 2)

I've found that "double negatives" of the general form if not A: B else: C (whether as statements or expressions) can be quite confusing / misleading; this isn't literally an if not .. else, but moving the not doesn't make the "double negative" go away.

So, in general, I just rewrite such constructs to if A: C else: B. In this particular case, if I did choose the ternary-operator form, I'd code it as

(2, 2) if self.maxTiles is None else self.maxTiles

On to the more general question: a = b or c is fine if and only if you really want to use c for any false value of b -- it's not fine to deal specifically with b being None. IOW, b or c is a better way to express

b if b else c

but it's not a way to express a similar expression where the core test is, instead, b is None. In theory, if you "know" that the only possible false value for b is None, they're semantically equivalent, but that strong "only possible false value" constraint will not be apparent to readers / maintainers of your code -- and if you have to add a comment to explain that, any conciseness advantages that or might claim are nullified... better, when feasible, to "say it in code", rather than have the code be obscure and need comments to clarify exactly what it's doing and when (comments that are really useful are rather those which explain, not the what and the when [[the code itself should show that!-)]], but rather the why when it's not obvious -- what's the application purpose being served by this specific tidbit of code functionality).

like image 96
Alex Martelli Avatar answered Dec 20 '22 10:12

Alex Martelli