Try Python, except, finally

It looks like I haven't quite mastered the handling of Exception yet. I am at a loss :( The following code sometimes returns this error:

File "applications/pingback/modules/plugin_h_pingback.py", line 190, in ping db(table.id==id_).update(status=status) UnboundLocalError: local variable 'status' referenced before assignment 

I expect that status will always be assigned a value. Could another exception be made (perhaps in an internal try ), and finally hide it?

 ... try: server_url = self._get_pingback_server(target) except PingbackClientError, e: status = e.message else: try: server = xmlrpclib.ServerProxy(server_url) status = server.pingback.ping(self.source, target) except xmlrpclib.Fault, e: status = e finally: db(table.id==id_).update(status=status) # <-- UnboundLocalError ... 

Thanks HC

+4
source share
2 answers

Your code does not always assign status. I see several ways that status may not be assigned, and I highlighted them below:

 try: server_url = self._get_pingback_server(target) except PingbackClientError, e: # If evaluating `e.message` raises an exception then status is not set. status = e.message # <--- here else: try: # If either of these two lines fails with something other than # xmlrcplib.Fault, then status is not set. server = xmlrpclib.ServerProxy(server_url) # <--- here status = server.pingback.ping(self.source, target) # <--- here # If xmlrpclib.Fault is not defined status is not set. except xmlrpclib.Fault, e: # <--- here status = e finally: db(table.id==id_).update(status=status) 

I suspect that the most likely place for the error is in the internal try block, where you only catch xmlrpclib.Fault , and not other types of exceptions.

+9
source

As a simple solution, I would initialize the status outside of any blocks:

 status = None try: # etc 

Then the status will always be tied. This will not solve the problem of any unhandled exception, but it will solve the UnboundLocalError.

(In addition, in the first block in which you confirm the status with e.message, in the next block you simply use the complete error e, not just the message.)

+3
source

Source: https://habr.com/ru/post/1332589/


All Articles