Search code examples
pythonperl

Variable scoping in python (for someone coming from perl)


I am new to python, I picked it up out of necessity - for the blender API.

As someone that comes from Perl (and somewhat less Javascript) I think am running into pitfalls WRT variable scoping. For example in Perl:

use strict;

my @list = ('a'..'z');

for my $v (@list) { print $v; }
print $v;

generates an error, while in Python

mylist=['a', 'b', 'c']

for v in mylist:
    print(v)

print (v)

works ok, and the last statement prints 'c'.

In Javascript:

var list = ['a', 'b', 'c']

for (let j=0; j < list.length; j++) { console.log(j, list[j]) }
console.log(j);

will throw an error ("j is not defined" - unless I omit let, in which case it behaves like Python)

So I get that for v in mylist i python defines a variable in the outer scope - a different behaviour from Perl (and partially javascript).

While I found most of the transition relatively straightforward, variable scoping (and its cousin, the ability to redefine builtin functions into a variable) confusing and hard to catch (no use strict - alas).

Hence the question: what are the key differences in variable scoping in Python that one should keep in mind when coming from Perl?

I'm specifically interested in scoping - the general transition question is well answered here and common pitfalls are nicely addressed here


Solution

  • It is mentioned in the The Python Language Reference, specifically for loops is Compound statements / The for statement. You will see the statement:

    Names in the target list are not deleted when the loop is finished, but if the sequence is empty, they will not have been assigned to at all by the loop.

    Also look under the Execution model for name binding.