last day (15 days later) » 

00:03
-3
Q: Faking LISP-like closures in Python?

BlenderBenderIn languages like Common Lisp you can use closures to hide global variables, as in (let ((my-global-variable '(foo bar')))) (defun f (x) (append my-global-variable x))) One possible way to do this in Python is def helper_function(): my_global_variable = ['foo', 'bar'] def f(x): ...

It does what I want; I checked it.
@StefanPochmann The code defines a callable function (f). I checked that it is callable as if it'd been defined simply using def. The line my_global_variable = [] introduces a variable binding that results in a closure when the 'internal' f is returned.
@StefanPochmann The point is that the variable my_global_variable is only visible from within the function f. This is why closures are so useful.
@CircArgs Please see my edit.
@user2357112 The variable is visible from within the inner function because a closure is created. My first example contained an error though, because "clojured" variables are read-only in Python (but that's enough for me).
@StefanPochmann Stop editing my question.
@TomKarzes The example has changed, there are no assignments in the inner function anymore. And yes, it tested it.
@CircArgs I want to have a constant object that is only visible from within the the function I define. The above code defines a function f in which the (immutable) variable my_global_var is visible. That is what I want. The only thing that's bothering me is that I need to define another function to achieve that.
@BlenderBender Stop lying. Your original "example" didn't demonstrate the thing at all, so the change didn't make it "better" but made it an actual example. Hence my correction of your statement.
@CircArgs Callable objects seem to essentially be what I want. Would you mind making that into an answer?
@CircArgs The error is because you are assigning to the variable i, but the variable i is immutable. Please evaluate my example in your interpreter to see that it works.
A much simpler way to do what your example does is simply def f(x): return ['foo', 'bar'] + x. Why not just do that?
@StefanPochmann Because the computation to be done by my real-world-f is actually way more expensive than that.
00:03
@BlenderBender So? I don't see the problem with that...
Maybe def f(x, prefix=['foo', 'bar']): return prefix + x then?
@StefanPochmann I don't want to recompute the object that would be in ['foo', 'bar']s place every time the function is called. That's why I want to use a global variable to store this object. However, since only this function makes use of this object, I'd prefer if it weren't visible outside it.
I'm not exactly sure what you mean by "Python closures aren't mutable". Sure, you can't assign to the my_global_variable name from within the nested f function (unless you use the nonlocal directive. But you can certainly mutate it, since it's a mutable object. Eg,
def helper_function():
    my_list = ['foo', 'bar']
    def f(x):
        my_list.append(x)
        return my_list[:]
    return f

f = helper_function()
a = f('baz')
print(a)
b = f('qux')
print(b, a)
#output
['foo', 'bar', 'baz']
['foo', 'bar', 'baz', 'qux'] ['foo', 'bar', 'baz']
Strictly speaking, Python doesn't really have variables. Please see Other languages have "variables", Python has "names". For a more in-depth discussion on this important aspect of the Python data model, take a look at Ned Batchelder's Facts and myths about Python names and values.
@BlenderBender If you do def f(x, prefix=['foo', 'bar']): return prefix + x then prefix=['foo', 'bar'] is only executed once, when the function definition of f is executed. It's a fairly common idiom for creating static data in Python.
Just to be crystal clear, prefix=['foo', 'bar'] will not be recalculated each time f is called.
00:22
@PM2Ring Heh... your second link explicitly disagrees with your first link. Ned calls "Python has no variables" a "myth" and says "The truth is that Python has variables".
@StefanPochmann :) I don't agree 100% with Ned, but that article has a lot of good stuff, and I must've linked it hundreds of times by now (I have it in a browser userscript). I occasionally use the "variable" terminology myself (it's hard to stop using it when you've been programming for 40+ years). I generally try to avoid using it on SO, but sometimes the alternatives just sound too awkward.
00:46
@PM2Ring I don't think there's anything wrong or problematic with calling them variables. Is there?
01:11
@StefanPochmann The problem is that it can give you the false impression that Python's data model is the same as that of more traditional languages. True, that's often not a problem, but it can be, when Python behaves differently to what you expect, and you try to explain it in terms of the "variable is a box" model.
Closely related to this is trying to understand Python in terms of machine architecture: memory locations, pointers, etc. Generally that's not fruitful unless you're interfacing with stuff that requires you to deal with pointers, etc. IMHO, it's better to adopt a more abstract perspective and embrace Python's data model on its own terms, as exemplified by the "Python doesn't have variables" article.
Bye for now.
02:14
Sure, if Python behaved differently to what I expect, that might be a problem. But I'd say it doesn't. I challenge you to show me an example concerning "variables" that surprises me :-P. And you even can use the "variable is a box" model, as b = a does copy the reference.
Maybe what you have in mind is something like C++ coders seeing b = a with lists in Python and thinking that the entire contents are duplicated? That's what I've seen several times. Doesn't have anything to do with the term "variable", though, it's just that they don't know how Python uses references. And usually all it takes to fix their mind is to remind them of C++'s pointers.
@PM2Ring (forgot the @... and can't seem to edit/delete anymore...)
 
17 hours later…
18:54
@StefanPochmann Perhaps we should be having this discussion over in the main Python chat room. But anyway...
One major difference between Python's a "a name is just a label for an object" and the "variable is a box" models is that a box has a definite size and datatype associated with it, so you are restricted in what you can put in a box, and it's an error to put the wrong size or type of thing into a box. In Python, the size & type of an object are properties of the object itself, the name(s) you label the object with don't know anything about that stuff.
And of course Python allows you to create objects that don't even have a name, although generally such objects are useless unless they are part of some collection which does have a name.
Off the top of my head I can't come up with a simple example that would surprise you (you already mentioned the "shallow copying" thing. And trying to think about this stuff while I've got a headache isn't easy. ;) ). But I remember when I was first learning Python being puzzled by some of its behaviour because I was trying to understand it in terms of a traditional C-like datamodel. And I've often seen questions on SO that show similar confusion.

last day (15 days later) »