简体   繁体   English

在尝试块中无法识别Pycharm变量分配

[英]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: PyCharm将上述最后一行标记为以下问题:

Local variable "driver" might be referenced before assignment 分配前可能会引用局部变量“ driver”

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? 有没有一种方法可以设置PyCharm,以便它可以在try块中看到分配?

Secondarily, can PyCharm figure out the type based on the return value of the function (in this case launch_browser() ) if it has docstrings? 其次,如果PyCharm具有文档字符串,是否可以根据函数的返回值(在本例中为launch_browser() )确定类型?

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. 只是让PyCharm理解try块中的任务而不必求助于创可贴。

EDIT 1: 编辑1:

A return in the except: block fixes the problem as far as PyCharm is concerned. 就PyCharm而言, except:块中的return解决了该问题。 I was working on something else and inadvertently commented it out. 我在做其他事情,无意间将其注释掉。 Proof that coding for 16 hours straight is a really bad idea... 证明连续进行16个小时的编码是一个非常糟糕的主意...

If launch_browser() fails, your code will error at the driver.get("http://www.example.com/") line. 如果launch_browser()失败,您的代码将在driver.get("http://www.example.com/")行处错误。 PyCharm is letting you know this. PyCharm让您知道这一点。

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. 避免这种情况的唯一方法是不执行except任何操作,例如在异常内抛出异常,或将所有依赖于driver放入else块中,这些操作仅在未捕获异常的情况下运行。 Eg 例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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