Question or problem about Python programming:
How can I make a variable inside the try/except block 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
How can I make the variable text available outside of the try/except block?
How to solve the problem:
Solution 1:
try
statements do not create a new scope, but text
won’t be set if the call to url lib.request.urlopen
raises the exception. You probably want the print(text)
line in an else
clause, so that it is only executed when 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 is supposed to be if the assignment to page
fails and you can’t call page.read()
. You can give it an initial value prior to the try
statement:
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 the else
clause:
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)
Solution 2:
As answered before there is no new scope introduced by using try except
clause, so if no exception occurs you should see your variable in locals
list and it should be accessible in current (in your case global) scope.
print(locals())
In module scope (your case) locals() == globals()
Solution 3:
Just declare the variable text
outside 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)