[Python-ideas] A "local" pseudo-function

Greg Ewing greg.ewing at canterbury.ac.nz
Wed May 2 03:34:18 EDT 2018


Steven D'Aprano wrote:
> y = 1
> def func():
>     x = 2
>     return x+y
> 
> Here, there's a local environment as well as an implicit global one. 
> Surely we don't want to call this a closure?

Python probably isn't the best choice of language for the
point you're making, because even top-level functions in
Python *do* carry a reference to their environment (the
dict of the module they were defined in).

C would be a better choice:

int y = 1;
int func(void) {
    int x = 2;
    return x + y;
}

int (*fp)() = func;

Even here, I don't think there's anything wrong with calling
fp a closure. It's just that it's a particularly simple form
of closure -- since there's only one global environment, we
don't need to bother explicitly carrying it around.

However, that doesn't mean all functions are closures. An
example of a non-closure might be a C++ member function pointer.
It points to a piece of code, but you can't use it on its own,
because it's missing a piece of environmental information
(a value for "this") that you need to supply by hand when
you call it.

> we have to consider what happens if we come 
> across a Pascal implementation which *doesn't* use a (code_address, 
> frame_pointer) pair. Is that no longer Pascal?

In anything that implements Pascal semantics, a function
parameter is going to have to be represented by *something*
that specifies both code and environment. Code alone is
not enough.

 > If we accept that "Pascal has closures", they're pretty crap closures,
 > since they don't let you do any of the interesting and useful things you
 > can do in languages with "real" closures like Scheme and Python.

Not all of them, but it can do some of them. They're more
useful than in Modula-2, for example, where nested functions
can't even be passed as parameters.

Anyway, that's why I said "a limited form of closure". You
could read that two ways: (1) It's totally a closure, but
there are limitations on what you can do with it (i.e. it's
not first class). Or (2) it has some of the characteristics
of a closure, but not all of them.

In my mind I tend towards (1), but it doesn't really matter.

-- 
Greg


More information about the Python-ideas mailing list