Some Python Examples
← prev | next →     Top-level ToC     /scoping.html     (printable version)

Because Python doesn’t have variable declarations, it’s not always obvious whether you’re assigning to an existing variable, or creating a new one:

# Perl
my $x = 0; # created a new variable
# Python
x = 0  # creating a new one
def outer():
    x = 1  # Ok, creating a new one. If we want to assign to global `x`,
    # we'd need to do: `global x = 1`.
    # ...
    def inner():
        x = 2  # Wait. Creating a new one, or referring to outer's `x`?
        nonlocal x = 3  # Ah. Here it's outer's `x`.

You don’t have this problem in language with normal variable declarations, though a global keyword could still be useful:

my $x = 0;

sub outer() {
    my $x = 1; # local,...
    $x = 1;    # or would assign to global `$x`.
    sub inner() {
        my $x = 2; # local, ...
        $x = 2;    # or outer's `$x`.
        # the global `$x` is shadowed.
    }
}