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

83,504

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)
Share:
83,504
x0x
Author by

x0x

Updated on August 23, 2020

Comments

  • x0x
    x0x almost 4 years

    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?

  • Kobi K
    Kobi K almost 10 years
    I think the OP wants a default value for text in case there is an exception. so maybe updating this answer with default value outside the try except scope or inside the else will help him.
  • Nathan Basanese
    Nathan Basanese almost 9 years
    // , Why would this be necessary? Python does not have a separate block-level scope for this try and except, AFAIK, and according to stackoverflow.com/questions/17195569/….
  • 4xy
    4xy over 6 years
    In the last snippet text will always eventually be assigned 'something' if no exception
  • Silidrone
    Silidrone almost 4 years
    "try statements do not create a new scope" this cleared up a lot of things for me, +1
  • santma
    santma over 3 years
    the "else" clause didn't work for me, but the initial value did. :D
  • Qiang Xu
    Qiang Xu about 3 years
    In the 3rd example, aside from the problem mentioned by @4xy, print(text) would still cause the original NameError if page.read().decode('utf8') raises an exception. It would only work if text = 'something' is moved into the except block.
  • nabil.adnan1610
    nabil.adnan1610 over 2 years
    Thank you! This one line "text won't be set if the call to url lib.request.urlopen raises the exception." cleared up the confusion I had for ages!