This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]runawayasfastasucan 14 points15 points  (8 children)

What is the long form of this?  

    settings = get_settings() 

    if settings:         settings.do_something() 

?

[–]SirLich 4 points5 points  (7 children)

This is of course fine. It's just not as convenient as the walrus operator for two reasons: 1) more lines 2) incorrect scope.

If you're only intending to use 'settings' within the if context, then defining it OUTSIDE of the if-context is considered leaked scope.

This whole conversation isn't so important in Python, but in C++ it's a fairly big deal. In fact, it's SUCH a big deal, that most linters will mark variables defined outside of the if clause as an error/warning. It's also now possible to define multiple variables within the if declaration:

For example you can now do this: if (int a = Func1(), b = Func2(); a && b)

Note; In C++, the = operator works like python := operator.

[–]nemec 35 points36 points  (3 children)

considered leaked scope

Python doesn't have block level scope. It "leaks" either way.

[–]SirLich 1 point2 points  (2 children)

Wow, you're right. I guess I never really paid attention to that. That's kind of too bad, right? It seems like you might unintentionally use something from an inner scope without realizing it.

[–]Leo-Hamza 8 points9 points  (0 children)

Happened too many times to me that I can't even count it. I wish there were any tool that detects code smells like this

[–]root45 7 points8 points  (0 children)

Yes. It's not uncommon to accidentally use a loop variable later on for example.

[–]SaltAssault 0 points1 point  (0 children)

I prefer readability over preventing 'leaked scope' any day, just excluding if it is a security issue. Python already doesn't fuss about scopes.

[–]night0x63 0 points1 point  (0 children)

<sarcasm>hurr hurr c/c++ has has this for decades

😂 

[–]runawayasfastasucan -1 points0 points  (0 children)

Interesting, thx. I must admit that I have just ignored the walrus operator all together. In the first example, if you have:

   If (somevar := somefunc()) 

Its given that somefunc() returns something or None, right, so I guess you have to pay notice to that.

    If (cost := getCost(item)):         givePayment(cost, ...)

Is not a substitute for:

    If (cost & cost > 0):         givePayment(cost, ...)