-1

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.

  • Please [edit] your question to show a [mcve]. I get [a totally different error](https://replit.com/@codeguru/GoldenrodTemporalDisassembly#main.py) when I run your code. – Code-Apprentice Sep 22 '22 at 00:57
  • 2
    In your own words, where the code says `with y.index("~") as _0:`, *what do you expect this to mean*? Why? – Karl Knechtel Sep 22 '22 at 00:58
  • 1
    Aside from that problem, what do you expect y[_0:_0] to do? How many elements do you think will be in the result? Why? (Answer: it will give an empty list, no matter what `y` contains.) – Karl Knechtel Sep 22 '22 at 00:59
  • `with` is used to make a context manager, which requires that the object in question have special methods such as `__enter__`. Your object does not have these methods. – John Gordon Sep 22 '22 at 00:59
  • I expected it to work as a temporary variable, as if renaming `y.index("~")` to `_0` for that small section of the code. – Dominic Miller Sep 22 '22 at 01:00
  • Please also see [Short description of the scoping rules?](https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules) - not also a duplicate, but important background information for your task. – Karl Knechtel Sep 22 '22 at 01:07
  • @DominicMiller Check out the link at the top of your question for an explanation of how with works. To do what you want, use regular assignment: `_0 = y.index("~")`. And then you'll need to figure out if `y[_0:_0]` does what you think it does. – Code-Apprentice Sep 22 '22 at 02:27
  • _I expected it to work as a temporary variable_ Why would you expect that? Is there some documentation stating it works that way? – John Gordon Sep 23 '22 at 23:46

1 Answers1

3

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.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • 1
    It's not unreasonable that they might assume that `with` is for creating a block-scoped variable, like Lisp's `let`. – Barmar Sep 22 '22 at 00:57