If cmd and cmd == 'x':

Hello,
I am trying to learn how to build a plugin. I forked Octoprint and I am on it.
In the code examples I am finding a curious expression that I would like to know the reason for its use:

if cmd and cmd == 'x':
do_something()

Why not just:

if cmd == 'x':
do_something()

One of the biggest reasons is that the first condition will be evaluated much faster which is important in the gcode hooks.

Thanks!
I imagined that this could be the intention but I thought that a case like that would be optimized in some way. Turns out not.

  • if x:
    4 LOAD_NAME 0 (x)
    6 POP_JUMP_IF_FALSE 16

  • if x is None:
    16 LOAD_NAME 0 (x)
    18 LOAD_CONST 0 (None)
    20 COMPARE_OP 8 (is)
    22 POP_JUMP_IF_FALSE 32

I also just read the advice not to put heavy computations in hooks. Well, little by little...

1 Like

That's how I learned...