5 Comments

So, do strings implement __iter__?

Expand full comment
author

>>> some_string = "hello"

>>> some_string.__iter__

<method-wrapper '__iter__' of str object at 0x1025e49b0>

So, yes, they do. Defining `__iter__()` is now the preferred way of making instances of a class iterable. So even though having `__getitem__()` is sufficient, most iterables will have `__iter__()` defined

Expand full comment

So, since everything is a class in Python, some behaviors get added at some point for default literals. Must look into this at the CPython level

Expand full comment
author

Not sure I follow the question fully. But yes, when you create a string such as "hello", you're effectively creating an instance of the str class, so it's a shorthand for str()

The str class will then have whatever special methods it needs to give it its properties, such as __iter__() to make it iterable, and so on

In this series, I'll be looking at other categories of data structures so I'll be exploring more of these special (dunder) methods that give objects these properties, such as __iter__() to make an iterable

Expand full comment

Was a side comment. Like i guess not all default types implement __iter__ like ints for example. For __iter__ to be added to strs, it has to be added at some point by the VM. Must look into this process.

Expand full comment