简体   繁体   中英

Is there a Python analog to this C++ construct?

In C++ (and C?) you can use variables in if statements while keeping them local. For example instead of this:

int out = func();
if (out == value) {
  // Do stuff
}

You can validate a value that you only need for a short block without adding the output variable to the calling context:

if (int out = func(); out == value) {
  // out is accessible here
}
// But out is not accessible here

I haven't been able to find anything like this in Python. Just curious if there was a way to do something similar.

C++ allows you to use = in an expression. Python does not.

PEP 572 implemented first in Python 3.8 introduces assignment expressions using what is informally known as the walrus operator, := .

It differs in the way that = works in C++ in that it doesn't limit the scope of the variable; you can still access it after the block where it was defined.

if (out := func()) == value:
    print(out)
print(out) # this works because out is still valid

To limit the scope you have to be explicit and del the variable.

if (out := func()) == value:
    print(out)
del out
print(out) # fails with an exception

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM