5 ms·
Bound and free variables: when I was taking a programming languages course, these concepts popped out at me as being incredibly important. But I had been progra
by lincolnq 18y ago
Bound and free variables: when I was taking a programming languages course, these concepts popped out at me as being incredibly important. But I had been programming for years without understanding that there was a distinction. Are they important for programming, or just for understanding how programming languages are implemented?
Regarding bound and free variables, I was reverse engineering Python's scoping semantics and discovered this little gem:
def a(x):
def b():
print x
x = 5
b()
a(3)
What do you expect? Prints 3, right? Nope. UnboundLocalError, because 'x' is referenced before it was assigned. It turns out that variable bindings in Python are all lifted to the enclosing 'scope' (usually a function block). So x is not a free variable in the 'print x' line... even though the interpreter claims it's not bound, either.
(This behavior is a royal pain to implement in an interpreter. You can't just recursively execute expressions; you have to scan the scope you're about to execute for free variables which are later bound in that scope.)
- aston 18y agoPython 3k adds a new keyword, nonlocal, which actually lets you print out x that way (you'd declare nonlocal x before printing). Check out PEP 3104: http://www.python.org/dev/peps/pep-3104/ http://www.python.org/dev/peps/pep-3104/