Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Error: AttributeError: __enter__ [duplicate]

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!

like image 238
Alex Quinto Avatar asked Jul 19 '18 16:07

Alex Quinto


People also ask

What is AttributeError__ enter__?

So, the AttributeError: __enter__ is raised when using a with statement with a class that does not have the __enter__ method. Note, that both __enter__ and __exit__ are required for a context manager, so if you only have __enter__ method you would run into the AttributeError: __exit__.

What is__ enter__ in Python?

Summary: Python calls the __enter__() magic method when starting a with block whereas the __exit__() method is called at the end. An object that implements both __enter__() and __exit__() methods is called a context manager. By defining those methods, you can create your own context manager.

How does Python handle attribute errors?

Attribute errors in Python are raised when an invalid attribute is referenced. To solve these errors, first check that the attribute you are calling exists. Then, make sure the attribute is related to the object or data type with which you are working.

What is a context manager Python?

A context manager usually takes care of setting up some resource, e.g. opening a connection, and automatically handles the clean up when we are done with it. Probably, the most common use case is opening a file. with open('/path/to/file.txt', 'r') as f: for line in f: print(line)


1 Answers

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

like image 76
BowlingHawk95 Avatar answered Sep 18 '22 23:09

BowlingHawk95