Is there a scenario where the container is not iterable, according to this graph?
Are containers always iterable?
Asked Answered
Depends on what you mean by always. According to collections.abc
- a container is an object that implements
__contains__
method - an iterable is an object that implements
__iter__
(or__getitem__
, as a fallback)
So, theoretically, no, you can implement a container that is not an iterable. However, all standard python containers (and most containers implemented by libraries) are also iterable.
All a container does is give you the if x in y
and if x not in y
syntax.
You could have like a Range(min: float, max: float)
that implements __contains__
as returning True for any number in the range, which would allow you to write if 3.14 not in provided_range
etc. And that would not be iterable.
The graph is a bit misleading in suggesting that {list, set, dict} comprehension
are the only interesting things to produce containers.
© 2022 - 2024 — McMap. All rights reserved.
collections.abc.ImmutableObject
(or something like that) which enforces certain abstract methods. Basically if you inherit from an ABC that enforces iteration than for sure it is iterable but you can't always assume third part containers are iterable. – Sacrilege__iter__
method – Masry