tushar.pyc Profile picture
Metaprogramming • Python • @DeepSourceHQ
Jan 10, 2023 9 tweets 3 min read
Python Dunder of the Day
Day 8: ✨__module__✨

Let's talk about the functools module first: It has some really useful tools, such as `cache`, which caches results from function calls.

🐍This can easily speed up code that has repeated calls to pure functions: It also has `partial()`, which lets you create partial functions: Functions whose some arguments have been pre-set.

✨It's helpful when you want to call some function repeatedly with some common arguments:
Jan 9, 2023 15 tweets 5 min read
🐍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
Jan 8, 2023 7 tweets 3 min read
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: 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:
Jan 7, 2023 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
Jan 6, 2023 9 tweets 3 min read
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
Jan 2, 2023 4 tweets 2 min read
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