◐ Shell
clean mode source ↗

bpo-12022: Change error type for bad objects in "with" and "async with" by serhiy-storchaka · Pull Request #26809 · python/cpython

For the code, why not pass the message format string to special_lookup() instead of repeating the same code four times?

It would save 3 lines in every of 4 caller places, but the helper function adds 14 lines. Also, I think that in future we can add slots for these methods, this will make the common code so simple that there will be nothing to share.

Also I think it would be useful to know which attribute is missing.

I think that in most cases the error is in using wrong object rather than missing of some dunder methods in the definition of user class. Traditional error messages:

>>> len(1)
TypeError: object of type 'int' has no len()
>>> list(1)
TypeError: 'int' object is not iterable

It does not say "requires an object with __iter__ method".

But it may be worth to add a hint in case of the object that has __enter__ but not __exit__. It is definitely an error in the user class definition.