Main Content

Python - access to variables in the outer scope

Archive - Originally posted on "The Horse's Mouth" - 2010-04-12 23:43:46 - Graham Ellis

In Python, variables are local to the block in which they're used unless declares in some other way. And that's good news, because the last thing you want in a substantial script is for data to "leak" between functions as can happen in default-accepting Perl or Lua.

But there is an exception ... if you use the EXISTING CONTENTS of a variable within a function in Python, and it's not set up within that function, it will be used from the enclosing scope instead. And this turns out to be very useful if (for example) you are sorting a list of the keys of a dictionary by value, prior to outputting them in order.

Here's an example:

beasts = { "Fluffy":4, "Gypsy":3, "Charlie":14,
    "Conga":5, "Roo":27, "Janet":154 }
   
def byage(second,first):
   return cmp(beasts[first],beasts[second])
   
bk = beasts.keys()
bk.sort(byage)
   
for bio in bk:
   print bio,beasts[bio]


See full source code [here]