Search code examples
pythonjsonenter

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__

Solution

  • 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.