Why does PyCharm think that this variable may be referenced before assignment while True loop?

Viewed 84

I have the following method that makes a HTTP GET request. I have added some error handling to it to ensure that it does not return a response unless there have been no network errors.

When the method is as follows Pycharm does not think that the response variable may be referenced before assignment:

    def requests_with_error_handling(self, url):
        while True:
            try:
                response = requests.get(url, headers=headers, proxies=random_proxy())
                break
            except Exception as e:
                self.pretty_print(e)
                time.sleep(1)               
        return response

However, when I add a continue statement at the bottom of the except block PyCharm does not like it and says that the response variable may be referenced before assignment, even though I believe both code blocks do the exact same thing and the continue statement is unnecessary since the the execution will move to the top of the while loop anyway if the continue is not present.

    def requests_with_error_handling(self, url):
        while True:
            try:
                response = requests.get(url, headers=headers, proxies=random_proxy())
                break
            except Exception as e:
                self.pretty_print(e)
                time.sleep(1)
                continue
        return response

Is this a bug with Pycharm or is my understanding of the program's control flow in Python incorrect?

1 Answers

all its effectively saying is that that variable is not guaranteed to exist within the scope it is returning at

In theory your loops should handle it... you could resolve it by adding response=None before the loop, that way the variable is guaranteed to be present in the scope of the return statement

as to your question, its neither a bug in pycharm nor is it you misunderstanding the control flow

Related