Are containers always iterable?
Asked Answered
P

2

7

enter image description here

Is there a scenario where the container is not iterable, according to this graph?

Polymorphous answered 11/7, 2019 at 12:52 Comment(4)
Technically you could implement a container yourself that is not iterable... or are you referring to a built in abstract base class?Sacrilege
@Error-SyntacticalRemorse, build in?Polymorphous
You can make a container class yourself but often you inherit from a class such as 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
for something to be iterable there is only one requirement , it needs to define __iter__ methodMasry
C
9

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.

Cornered answered 11/7, 2019 at 13:9 Comment(0)
R
1

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.

Rosenkrantz answered 6/6, 2021 at 2:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.