Reputation: 3955
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...
Upvotes: 1
Views: 1125
Reputation: 7358
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
, e.g. 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. E.g.
try:
driver = launch_browser()
except:
print "Browser launch failed"
else:
driver.get("http://www.example.com/")
Upvotes: 3