Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Error: "AttributeError: __enter__"

Tags:

python

json

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__
like image 973
Caio Alexandre Avatar asked Nov 30 '18 20:11

Caio Alexandre


2 Answers

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.

like image 102
Lukas Graf Avatar answered Oct 30 '22 07:10

Lukas Graf


I got this error at this line:

with concurrent.futures.ProcessPoolExecutor as executor:

missing brackets was the issue

with concurrent.futures.ProcessPoolExecutor() as executor:
like image 37
a20 Avatar answered Oct 30 '22 07:10

a20