63

I receive the attribute error when I try to run the code.

    with ParamExample(URI) as pe:
    with MotionCommander(pe, default_height=0.3)as mc:

This is where the error occurs.

Traceback (most recent call last):
File "test44.py", line 156, in <module>
with ParamExample(URI) as pe:
AttributeError: __enter__

That is the traceback that I receive in my terminal. If you need to see more of my code, please let me know. Any help is appreciated, thank you!

scharette
  • 9,437
  • 8
  • 33
  • 67
Alex Quinto
  • 651
  • 1
  • 5
  • 3
  • 10
    You need to implement `__enter__` in your class and return self in it. – scharette Jul 19 '18 at 16:31
  • 1
    What are you expecting the `with Something(...) as something:` construct to do, exactly? – NPE Jul 19 '18 at 16:33
  • 18
    Also happens when you forget parenthesis eg: `with Session:` instead of `with Session()` while using tensorflow – Adav May 27 '19 at 15:30
  • i got the same error when I was executing /tmp folder –  Jul 22 '19 at 09:51
  • 2
    Or if anyone is doing asynchronous programming, don't forget to put: `async with` – Stevo Aug 24 '20 at 08:22
  • 1
    I doubt someone (except those who won't never make the same mistake) will be able to understand how the linked "duplicate" is actually answering the question on this page, or even whether there is a relationship between the two questions. And no other answer comes close to @BowlingHawk95 's one. – mins Jan 22 '21 at 16:12
  • And also happens when you use `read()` inside `with open` so you should not do that – Mohsen Hrt Mar 26 '21 at 05:31

1 Answers1

60

More code would be appreciated (specifically the ParamExample implementation), but I'm assuming you're missing the __enter__ (and probably __exit__) method on that class.

When you use a with block in python, the object in the with statement gets its __enter__ method called, the block inside the with runs, and then the __exit__ gets called (optionally with exception info if one was raised). Thus, if you don't have an __enter__ defined on your class, you'll see this error.

Side note: you need to either indent the second with block so it's actually inside the first, OR replace these two lines with

with ParamExample(URI) as pe, MotionCommander(pe, default_height=0.3) as mc:

which is the same as nesting these two context managers (the name of the objects used by with blocks).

BowlingHawk95
  • 1,518
  • 10
  • 15
  • As far as http://blog.lambdaconcept.com/doku.php?id=nmigen:nmigen_sim_testbench is concerned (same problem in tutorial) using "with" with Simulator is deprecated - just create and assign and make "process" as normal function – Virtimus Jan 06 '21 at 17:37