How to make a variable inside a try / except public object?

How can I make a variable inside a try / block except public?

import urllib.request try: url = "http://www.google.com" page = urllib.request.urlopen(url) text = page.read().decode('utf8') except (ValueError, RuntimeError, TypeError, NameError): print("Unable to process your request dude!!") print(text) 

This code returns an error

NameError: name 'text' not defined

How to make variable text available outside of try block / Except?

+34
scope python local-variables try-except
source share
4 answers
Operators

try does not create a new scope, but text will not be set if the url lib.request.urlopen call url lib.request.urlopen throws an exception. You probably need the print(text) in the else clause, so it will only be executed if there is no exception.

 try: url = "http://www.google.com" page = urllib.request.urlopen(url) text = page.read().decode('utf8') except (ValueError, RuntimeError, TypeError, NameError): print("Unable to process your request dude!!") else: print(text) 

If text needs to be used later, you really need to think about what its value should be if the page assignment fails, and you cannot call page.read() . You can give it an initial value before the try :

 text = 'something' try: url = "http://www.google.com" page = urllib.request.urlopen(url) text = page.read().decode('utf8') except (ValueError, RuntimeError, TypeError, NameError): print("Unable to process your request dude!!") print(text) 

or in else :

 try: url = "http://www.google.com" page = urllib.request.urlopen(url) text = page.read().decode('utf8') except (ValueError, RuntimeError, TypeError, NameError): print("Unable to process your request dude!!") else: text = 'something' print(text) 
+46
source share

As already mentioned, a new shell is not introduced using the try except clause, so if there is no exception, you should see your variable in the locals list, and it should be available in the current (in your case global) area.

 print(locals()) 

In the module area (your case) locals() == globals()

+3
source share

Just declare the text variable outside of try except block,

 import urllib.request text =None try: url = "http://www.google.com" page = urllib.request.urlopen(url) text = page.read().decode('utf8') except (ValueError, RuntimeError, TypeError, NameError): print("Unable to process your request dude!!") if text is not None: print(text) 
+1
source share

you can try the following:

 try: url = "http://www.google.com" page = urllib.request.urlopen(url) text = page.read().decode('utf8') except (ValueError, RuntimeError, TypeError, NameError): text = "Unable to process your request dude!!" else: text = "" finally: print text 
0
source share

All Articles