python - Traceback: AttributeError:addinfourl instance has no attribute '__exit__' -
from urllib import urlopen urlopen('https://www.python.org') story: story_words = [] line in story: line_words = line.split() words in line_words: story_words.append(word) error message:
traceback (most recent call last): file "<stdin>", line 1, in <module> attributeerror: addinfourl instance has no attribute '__exit__' i not understanding what's wrong above code , how resolve it?
system information : python 2.7 in ubuntu oracle virtual box.
that error caused line:
with urlopen('https://www.python.org') story: to fix this, replace line following line:
story = urlopen('https://www.python.org') additional info on error
why happening?
to make with ... as statement work object, context manager object must implemented. means object/class must have __enter__ , __exit__ methods defined it.
the attributeerror raised because there isn't context manager implemented urlopen (i.e. doesn't have __enter__ , __exit__ methods defined it).
since author of urlopen hasn't implemented that, there's not can it, except for:
- either don't use
with...asstatement. - or, if must, can use
contextlib.closing(thanks @vaultah provided solution in comments below). automatically implements context manager object, thereby allowing usewith...asstatement.
how implement context manager?
you can implement context manager defining __enter__ , __exit__ methods object/class.
do read these docs on context managers.
example:
# example without context manager # raise attributeerror >>> class person(object): def __init__(self, name): self.name = name >>> person("john doe") p: print p.name >>> attributeerror: __exit__ above, got attributeerror because haven't implemented context manager person. below how context manager implemented.
# implementing context manager >>> class person(object): def __init__(self, name): self.name = name def __enter__(self): # value returned method # assigned variable after ``as`` return self def __exit__(self, exc_type, exc_value, exc_traceback ): # returns either true or false # don't raise exceptions in method return true >>> person("john doe") p: print p.name >>> "john doe"
Comments
Post a Comment