Caio Alexandre
Caio Alexandre

Reputation: 153

Python Error: "AttributeError: __enter__"

So, I can't load my json file and I don't know why, can anyone explain what I'm doing wrong?

async def give(msg, arg):
    if arg[0] == prefix + "dailycase":
                with open("commands/databases/cases.json", "r") as d:
                     data = json.load(d)

For some reason I'm getting this error:

    with open("commands/databases/cases.json", "r") as d:
AttributeError: __enter__

Upvotes: 13

Views: 64331

Answers (4)

pbatey
pbatey

Reputation: 1451

My problem was that I was expecting os.open to work like the built-in open...

This results in AttributeError: __enter__

import os 
with os.open('out.txt', os.CREAT) as f:
  f.write('hello world')

This does not

with open('out.txt', 'w') as f:
  f.write('hello world')

I suppose it would be easy enough to cause the OP problem with from os import open.

Upvotes: -1

Chris Pollitt
Chris Pollitt

Reputation: 61

In my case, I was intentionally defining a custom with function called stopwatch

with stopwatch('upload %d bytes' % len(data)):
    ...code...

And so had to add:

import contextlib

and prefix the custom function definition as follows:

@contextlib.contextmanager
def stopwatch(message):
    ...code...

Upvotes: 2

a20
a20

Reputation: 5661

I got this error at this line:

with concurrent.futures.ProcessPoolExecutor as executor:

missing brackets was the issue

with concurrent.futures.ProcessPoolExecutor() as executor:

Upvotes: 21

Lukas Graf
Lukas Graf

Reputation: 32650

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.

Upvotes: 22

Related Questions