The semantic equivalent of async for

In the docs related to async for syntax in Python 3.5, I realized that it was introduced to iterate over the expected iterator.

There is something in the semantic equivalent that I don't get, following the description:

 iter = (ITER) iter = type(iter).__aiter__(iter) running = True while running: try: TARGET = await type(iter).__anext__(iter) except StopAsyncIteration: running = False else: BLOCK else: BLOCK2 

What does the string iter = type(iter).__aiter__(iter) do? Why is this necessary?

+5
source share
1 answer

Magic methods in python, for example. __add__ , always looking for a class . For example, len(foo) actually calls the solution type(foo).__len__(foo) . This means that it will never use foo.__len__ if __len__ defined on foo . [1]

Since __aiter__ is a magic method, it always looks like type(foo).__aiter__(foo) .


Search example:

 class Thingy(object): def __len__(self): return 10 lengthy_thingy = Thingy() lengthy_thingy.__len__ = lambda self: 20 print(len(lengthy_thingy)) # gives `10` print(lengthy_thingy.__len__(lengthy_thingy)) # gives `20` instead print(type(lengthy_thingy).__len__(lengthy_thingy)) # gives `10` as for using `len` 
+3
source

All Articles