DEV Community

Discussion on: Rust, Iterators, and Skill Regression

Collapse
 
voanhcuoc profile image
Khoa Che

Last week I was fucked up, I need to tear down some connection in Python and this is what spawned out of my normal functional programming brain:

map(teardown, connections)

My code didn't work, and I spent 1 hour to realize the teardown function never run. I end up with:

for damn in map(teardown, connections):
    pass

In python3, map returns an iterator and functions inside never run until being iterated on. In my opinion, this is inconsistent behavior: Python is sync by default, so map should be sync, asynchronous map should be mapAsync or be imported from asyncio. Why makes such simple thing so surprising?

Collapse
 
rpalo profile image
Ryan Palo

Well in general, I would say that in Python at least, you should probably almost never need the map function. If you’re using map, you probably want a for loop or a list comprehension. Especially if you’re not using the result of the teardown function, it probably ought to be:

for connection in connections:
teardown(connection)

What do you think?

Collapse
 
voanhcuoc profile image
Khoa Che

Thank you, I knew it and did it since the first days I learn programming. It's more a matter of preference, the functional programming way seems more natural and straightforward to me.

IFAIK, FP isn't a recommended paradigm in Python, even Guido has said he wants to remove map, reduce and filter. Now I think he's right, anyone wishes for FP favor should use a third party module rather than rely on the standard library.

Collapse
 
lauromoura profile image
Lauro Moura

A better name for this behaviour would be lazy instead of asynchronous.

An async operation generally means stuff happening "behind the scenes/at the same time", while a lazy operation delivers results "on demand", which is the case for the iterators.

Collapse
 
voanhcuoc profile image
Khoa Che

Yeah, lazy evaluation in contrast to eager evaluation.

Thank you!