[issue30352] The 'in' syntax should work with any object that implements __iter__
Edouard KLEIN
report at bugs.python.org
Fri May 12 08:18:04 EDT 2017
New submission from Edouard KLEIN:
In this StackOverflow question:
http://stackoverflow.com/questions/43935187/how-come-an-object-that-implements-iter-is-not-recognized-as-iterable/43935360#43935360
the question of why an object that implements __iter__ through __getattr__ does not work with the "in" syntax is raised. The accepted answer is that the interpreter checks for __iter__ instead of just calling it.
If that's the case, I think that:
- Either the behaviour of the interpreter should be changed to accept any object that implements __iter__, regardless of how,
- Or, if there is a technical reason why the interpreter can't change its behavior, the documentation https://docs.python.org/3/library/stdtypes.html#iterator-types should make it clear that __iter__ must be hard coded into the object.
Here is the code of the object that arguably should be iterable but is not:
class IterOrNotIter:
def __init__(self):
self.f = open('/tmp/toto.txt')
def __getattr__(self, item):
try:
return self.__getattribute__(item)
except AttributeError:
return self.f.__getattribute__(item)
IterOrNotIter().__iter__().__next__() # Works
'a' in IterOrNotIter() # Raises a TypeError
----------
components: Interpreter Core
messages: 293547
nosy: Edouard KLEIN
priority: normal
severity: normal
status: open
title: The 'in' syntax should work with any object that implements __iter__
type: behavior
versions: Python 3.6
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue30352>
_______________________________________
More information about the Python-bugs-list
mailing list