[Tutor] Functional Programming in Python

Danny Yoo dyoo at hashcollision.org
Thu Apr 2 20:52:40 CEST 2015


>> What are your thoughts on Functional in Python?
>> Currently I am re-writing functions to reduce their side effects.
>> I am also removing the state from objects and putting it into a closure
>> type function.
>
> That doesn't remove state, it just moves it to a different place.
>
> However, encapsulating state inside a closure, or an object, it often
> the most effective and natural way to deal with a problem. Better than
> passing around long and confusing numbers of variables!

Theoretically, I'd agree with this.  But engineering-wise, I'd
recommend explicit structures or objects if possible when representing
state.

Arbitrary lambdas are unconstrained in what they do.  They are raw
material for computation.  You can do pretty much anything with them.
That aspect is often heralded as a positive.  But that means that we
often need to do more work to make lambdas do things that we'd
otherwise do with other built-in features of the language.


Let's make this concrete.  If we want to represent a coordinate, a
pair of numbers, we could use raw closures for this...

################################
def pair(x, y):
    def dispatch(msg):
        if msg == 'x':
             return x
        if msg == 'y':
             return y
    return dispatch

p = pair(3, 4)
print p('x')
print p('y')
################################

And this works!


But there's already a feature in the language that does this kind of
aggregation.

################################
class pair(object):
    def __init__(self, x, y):
        self.x, self.y = x, y

p = pair(3, 4)
print p.x
print p.y
#################################

This is something that folks expect and is well supported and understood.


This is not to say that closures are bad.  It's just to point out that
just because functional programs use closures quite a lot, doesn't
automatically mean closures are the most appropriate tool for
everything.  If there are parts of the language that already do the
sort of thing you're trying to accomplish, it might be good to reuse
those parts, rather than reinvent the universe.


More information about the Tutor mailing list