Why does this give me an attribute error?

36 Views Asked by At

I'm working on a text-based adventure game, and this code searches through a room file and pulls a substring from it that adds it to a list of enemies.

with y.index("~") as _0:
    self.room_enemies.append(y[_0:_0])
    print(y[_0:_0])

However, when I run it, it gives me this:

AttributeError: __enter__

If this isn't enough information for a good answer, please let me know.

1

There are 1 best solutions below

1
Silvio Mayolo On

with is not variable assignment. If you want to assign variables, use the equal sign.

_0 = y.index("~")

(Though _0 is an extremely bizarre variable name)

with is used with context managers, such as opened files or database connections, and it's sort of like Java's try-with-resources block. It won't work on arbitrary data types that haven't been designed with the construct in mind.