Accessing the outer scope in Python 2.6

Define the variables outside of the functions and use the global keyword.

s, n = "", 0

def outer():
    global n, s
    n = 123
    s = 'qwerty'
    modify()

def modify():
    global n, s
    s = 'abcd'
    n = 456

Sometimes I run across code like this. A nested function modifies a mutable object instead of assigning to a nonlocal:

def outer():
    s = [4]
    def inner():
        s[0] = 5
    inner()

This is not how nonlocal works. It doesn't provide dynamic scoping (which is just a huge PITA waiting to happen and even more rarely useful than your average "evil" feature). It just fixes up lexical scoping.

Anyway, you can't do what you have in mind (and I would say that this is a good thing). There's not even a dirty but easy hack (and while we're at it: such hacks are not discouraged because they generally perform a bit worse!). Just forget about it and solve the real problem properly (you didn't name it, so we can't say anything on this).

The closest you could get is defining some object that carries everything you want to share and pass that around explicitly (e.g. make a class and use self, as suggested in another answer). But that's relatively cumbersome to do everywhere, and still hackery (albeit better than dynamic scoping, because "explicit is better than implicit").

Tags:

Python

Scope