Most likely, you have reassigned the Python builtin open
function to something else in your code (there's almost no other plausible way this exception could be explained).
The with
statement will then attempt to use it as a context manager, and will try to call its __enter__
method when first entering the with
block. This then leads to the error message you're seeing because your object called open
, whatever it is, doesn't have an __enter__
method.
Look for places in your Python module where you are re-assigning open
. The most obvious ones are:
- A function in the global scope, like
def open(..)
- Direct reassignment using
open =
- Imports like
from foo import open
or import something as open
The function is the most likely suspect, because it seems your open
is actually a callable.
To aid you finding what object open
was accidentally bound to, you can also try to
print('open is assigned to %r' % open)
immediately before your with
statement. If it doesn't say <built-in function open>
, you've found your culprit.
open
defined to something else in your code? Either by assignment (open =
) or by importing it from somewhere (from place import open
)?print(open.__doc__)
... if you don't see a massive blob of internal python text, starting with "Open file and return a stream", then his theory is correct.open
by just doingimport io
, and testingopen is io.open
(on Python 3, the built-inopen
aliasesio.open
).__enter__
isn't looked up until the item in question is fully constructed; odds are theopen
call succeeded, it just referenced the wrongopen
, but once it succeeds, that wrongopen
isn't on the call stack anymore.