Python Error: AttributeError: __enter__ [duplicate]
Asked Answered
B

1

68

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!

Biceps answered 19/7, 2018 at 16:30 Comment(7)
You need to implement __enter__ in your class and return self in it.Bernadinebernadotte
What are you expecting the with Something(...) as something: construct to do, exactly?Hackbut
Also happens when you forget parenthesis eg: with Session: instead of with Session() while using tensorflowChopper
i got the same error when I was executing /tmp folderHorrocks
Or if anyone is doing asynchronous programming, don't forget to put: async withTrochee
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.Provision
And also happens when you use read() inside with open so you should not do thatHeppman
E
65

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

Enchanting answered 19/7, 2018 at 16:34 Comment(1)
As far as 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 functionSmokedry

© 2022 - 2024 — McMap. All rights reserved.