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
NameError: name 'text' is not defined
How can I make the variable text available outside of the try/except block?
In the except case text is never assigned. You could set text = None in that block or before the try . This isn't a scope problem.
The built-in try function does not create its own scope. Modules, classes, and functions create scope. A complete description of Python scopes and namespaces in the docs.
What you need to do is declare your variable outside of the try scope. Before the try scope so it the variable still exists in your except block. This will raise the exception but x will still have scope (lifetime) and will print out in the 2nd exception case.
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)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With