I avoid the y if x else z
syntax when I can. It's inherently an ugly, unintuitive syntax, and one of the bigger mistakes in Python's design. It's an out-of-order expression: x is evaluated before y. It's unintuitive; it's naturally read as "if x then y, else z". C's syntax gives us a decades-established, universally-understood order for this: x? y:z
. Python got this one very wrong.
That said, ternary syntax is the wrong mechanism for supplying a default anyway. In self.maxTiles if self.maxTiles is not None else (2, 2)
, note the redundancy: you have to specify self.maxTiles
twice. That's repetitive, so it takes more work to read the code. I have to read it twice to be sure it doesn't say, for example, self.minTiles if self.maxTiles is not None else (2, 2)
.
self.maxTiles or (0,2)
avoids these problems; it's perfectly clear at a glance.
One caveat: if self.maxTiles is ()
or 0
or some other false value, the result is different. This is probably acceptable based on what you seem to be doing, but keep this in mind. It's an issue when providing a default for a boolean or an integer, and you really do need the is None
test. For those I prefer a simple conditional, but will sometimes fall back on a ternary expression.
Edit; a clearer way of writing the conditional version is:
if self.maxTiles is None:
maxX, maxY = 2, 2
else:
maxX, maxY = self.maxTiles