0

I'm kinda new to python and this time I'm using it for AI in games programming which includes graphics.

I saw an example of code in the book which is

def __init__(self, m=None):
    if isinstance(m, Matrix33):
        m = list(m._m)
    self._m = m or [1., 0., 0., 0., 1., 0., 0., 0., 1.]

how does python situate OR on the assignment of a variables without any condition?

Robert Tirta
  • 2,593
  • 3
  • 18
  • 37
  • 1
    It will check if `m` is empty list or `None` and if so set the list `[1.0, ...]` to `self._m`. Otherwise `self._m` will be set to `m` – kuro May 02 '17 at 11:29
  • @kuro, if that's the answer, please post it as an answer. – Kevin May 02 '17 at 11:45
  • Possible duplicate of [Does Python support short-circuiting?](http://stackoverflow.com/questions/2580136/does-python-support-short-circuiting) – mkrieger1 May 02 '17 at 11:50

1 Answers1

0

I think your expectation is that the boolean operator or returns True or False. But it doesn't. or returns the first of its operands to evaluate to True.

So:

1 or 0 --> 1 (treated as True if you use it where a bool is expected)

0 or 'B' --> 'B' (treated as True if you use it where a bool is expected)

The example you cite is an idiom that you will find in most languages that automatically cast non-boolean datatypes to booleans, a long tradition that goes back to PL/1. The idiom can lead you astray if you are expecting the first operand to contain either None or a valid value, and the valid value you get is actually zero.

You could also express it more explicitly as

self._m = m if m else [1., 0., 0., 0., 1., 0., 0., 0., 1.]
BoarGules
  • 16,440
  • 2
  • 27
  • 44