Tushar Sadhwani Profile picture
Jan 7 7 tweets 3 min read
Python Dunder of the Day 5: ✨__next__✨

We learned about __iter__ yesterday, and how it is used to create custom iterables.

But the way we did it was sort of a hack: By using `yield`, we just returned a generator from `__iter__()`.

In general, an iterable returns an iterator: Image
So to create an iterable, we need to first create an iterator.

🐍To create an iterator, you just need a class that defines a `__next__()` method. that method should just return the next value: Image
If we return this iterator object from our `MyIterable` class, our class will now forever return 42: Image
Let's look back at how a `for` loop works internally: It gets the iterator from `__iter__`, and then repeatedly calls `next()` on it.

A `next(i)` call is practically the same as `i.__next__()`, which means we have to make `__next__` return the next value.
Knowing all this, we can create an iterator that returns one item from a sequence, one by one, by getting `items[0]`, `items[1]`, ... until it runs out.

✨Here's how: Image
The previous example is big, but simple in essence:

- The iterator starts with a list of items and an index of 0
- On every __next__() call, it returns the next number in the list
- Once it runs out, it raises StopIteration

✨That's the internals of iteration.

e.g. a Reversed: Image
Now note that:
- An iterable needs to return an iterator in `__iter__`
- An iterator needs to define a `__next__`

So if you make a class that defines both, and make `__iter__(self)` just returns `self`, it'll work the same way.

✨So objects can be both iterable and an iterator: Image

• • •

Missing some Tweet in this thread? You can try to force a refresh
 

Keep Current with Tushar Sadhwani

Tushar Sadhwani Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @sadhlife

Jan 9
🐍Python Dunder of the day
Day 5: ✨__length_hint__✨

Let's do a little obscure one this time. Did you know that dunders can have multiple words?

Anyway, take a look at this code: Image
Now look at this code that does the same thing:

You'd expect this second example to be a bit faster because the generator is being iterated over in C code rather than Python code.

✨And you'd be right, this is faster: Image
But the surprising thing is, it's almost 4 times faster: Image
Read 15 tweets
Jan 8
Python Dunder of the day 6: ✨__mro__✨

Compared to the last two, this one is much simpler!
`mro` stands for "Method Resolution Order", and exists on all classes: Image
The `__mro__` is a tuple of classes, and it always starts with the class itself.
What it actually represents, is the order in which it tries to find a method call.

Hence the name 🤷‍♂️

It's better with an example, let's understand how methods are stored: Image
By using `vars()`, which turns an object into a dictionary, we can see that a class' methods are stored on the class itself.

✨Makes sense so far? Not for long, now let's look at the `bool` class: Image
Read 7 tweets
Jan 6
Python Dunder of the Day 4: ✨__iter__✨

Python's for loops are extremely convenient, as they get rid of the common "Index out of bound" errors.

That's because Python's for loops aren't index based, they're _iterator based_: Image
Note that the code above says `iterable`, not `iterator`.
Both of them are completely different.

🐍Python has a builtin function `iter()`, which takes an *iterable* and turn it into an *iterator*.

Read that again, just in case. Here's it in code form: Image
You probably already know what an iterable is:

✨Anything that you usually put in a for loop, is an iterable.

Everything from `range()`, lists, tuples, sets, generators, and even things like the output of `reversed()` are all iterators. Image
Read 9 tweets
Jan 2
Python Dunder of the Day 1: ✨__name__✨

You've probably seen code like this before: Image
__name__ is supposed to be the name of the current module.

When you import a module: `import foo`, the code inside the module will have __name__ set to "foo". Image
The only exception is for the module that was run by the `python` command itself.

✨Since the running python file wasn't imported, it doesn't have a "module" name, per se. So it defaults to '__main__': Image
Read 4 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Don't want to be a Premium member but still want to support us?

Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal

Or Donate anonymously using crypto!

Ethereum

0xfe58350B80634f60Fa6Dc149a72b4DFbc17D341E copy

Bitcoin

3ATGMxNzCUFzxpMCHL5sWSt4DVtS8UqXpi copy

Thank you for your support!

Follow Us on Twitter!

:(