Is there a way to change the closure of a python function?

Gregory Ewing greg.ewing at canterbury.ac.nz
Wed Sep 28 04:52:52 EDT 2016


Chris Angelico wrote:
>
> <greg.ewing at canterbury.ac.nz> wrote:
> 
>>* No side effects (new variable bindings may be created, but
>>  existing ones cannot be changed; no mutable data structures).
> 
> If that's adhered to 100%, the language is useless for any operation
> that cannot be handled as a "result at end of calculation" function.

Surprisingly, that turns out not to be true. Modern
functional programming has developed some very elegant
techniques for expressing state-changing operations in
a functional way, using things they call monads.

Essentially you write the whole program in continuation-
passing style, with a state object being passed down an
infinite chain of function calls.

None of the functions ever return, so there's no
danger of an "old" state being seen again after the state
has changed. This allows in-place mutations to be
performed as optimisations; it also allows I/O to be
handled in a functional way.

> You can't produce intermediate output. You can't even produce
> debugging output (at least, not from within the program - you'd need
> an external debugger). You certainly can't have a long-running program
> that handles multiple requests (eg a web server).

Well, people seem to be writing web servers in functional
languages anyway, judging by the results of googling for
"haskell web server". :-)

>>* Syntactic support for currying.
> 
> Is that really such a big deal?

It is when higher-order functions are such a fundamental
part of the ecosystem that you can hardly take a breath
without needing to curry something.

> Unless you're deliberately defining
> "functional language" as "clone of Haskell" or something, there's no
> particular reason for this to be a requirement.

It's not *my* definition, I'm just pointing out what
the term "functional language" means to the people
who design and use such languages. It means a lot more
than just "a language that has functions". If that's
your definition, then almost any language designed
in the last few decades is a functional language, and
the term is next to meaningless.

> Python is predominantly a *practical* language. Since purely
> functional programming is fundamentally impractical, Python doesn't
> force us into it.

The point is that a true functional language (as
opposed to just "a language that has functions") *does*
force you into it. Lack of side effects is considered
an important part of that paradigm, because it allows
programs to be reasoned about in a mathematical way.
If that's not enforced, the point of the whole thing
is lost.

The fact that Python *doesn't* force you into it means
that Python is not a functional language in that sense.

-- 
Greg



More information about the Python-list mailing list