简体   繁体   中英

Pycharm variable assignment not recognized inside try block

try:
    driver = launch_browser()
except:
    print "Browser launch failed"

driver.get("http://www.example.com/")

The last line above is flagged by PyCharm with the following issue:

Local variable "driver" might be referenced before assignment

However, something like this makes the error go away:

driver = None
try:
    driver = launch_browser()
except:
    print "Browser launch failed"

driver.get("http://www.example.com/")

Is there a way to setup PyCharm so that it will see the assignements inside try blocks?

Secondarily, can PyCharm figure out the type based on the return value of the function (in this case launch_browser() ) if it has docstrings?

BTW, code works just fine in both cases. It's just a matter of getting PyCharm to understand the assignment inside the try block without having to resort to a band-aid.

EDIT 1:

A return in the except: block fixes the problem as far as PyCharm is concerned. I was working on something else and inadvertently commented it out. Proof that coding for 16 hours straight is a really bad idea...

If launch_browser() fails, your code will error at the driver.get("http://www.example.com/") line. PyCharm is letting you know this.

The only way to avoid this is by not executing anything below the except , eg throwing an exception inside it, or putting everything that relies on driver inside an else block, which will only run if no exception is caught. Eg

try:
    driver = launch_browser()
except:
    print "Browser launch failed"
else:
    driver.get("http://www.example.com/")

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