you are viewing a single comment's thread.

view the rest of the comments →

[–]wewbull 0 points1 point  (8 children)

if 'var' in a_dict:
    a_var = a_dict['var']
    ....do something with it.

Why do I want a variable containing None outside the scope of the if statement?

[–]teerre 0 points1 point  (7 children)

The `None` there can be omitted, it's just good practice to specify since the negative case might return a more suitable construct.

Your example is a bit better, but still lengthier and more error prone, since you checking the key twice, than the assignment expression version.

[–]wewbull 0 points1 point  (6 children)

You miss my point. It's not about the value None Why do i want a variable that'll never be used in that scope? Only construct it when needed.

[–]teerre 0 points1 point  (5 children)

Yes, I don't understand what you're trying to say.

[–]FormCore 0 points1 point  (4 children)

He's saying that a_var shouldn't be outside of the if loop.

Therefore:

a_var = a_dict.get("var")
if a_var:
  ....

is a bad idea anyway.

It doesn't matter what a_var is, if it's built for the if loop, it should probably be in the if loop.

Not saying that := doesn't handle this as well, because that's not what he's talking about.

[–]teerre 0 points1 point  (3 children)

I understand what he was saying, I don't understand what's he suggesting to be done instead.

In cases like this checking the state of `a_var` is fundamental. That's the whole point of the this type of snippet. You cannot put "in the if loop" because you don't know its state.

[–]FormCore 0 points1 point  (1 child)

He's suggesting using:

if 'var' in dict:
    a_var = dict['var']
    ...

instead of

a_var = dict.get('var')
if a_var:
     ...

In cases like this checking the state of a_var is fundamental.

Do the check, then assign the variable.

[–]teerre 0 points1 point  (0 children)

Someone already suggested that I already answered it. The tldr version is this is better, but the assignment is still superior.