Main Content

Sharing variables with functions, but keeping them local too - Python

Archive - Originally posted on "The Horse's Mouth" - 2008-09-09 23:48:12 - Graham Ellis

""" One of the big issues with any programming language is how in shares (scopes) variables between blocks of code. On one hand there's a desire to have variables easily accessible without a lot of passing around. On the other hand there's the need to keep information in vary different parts of you code apart, with a variable name you happen to have used twice not resulting in a memory location being shared between two pieces of code which are otherwise independent of each other.

With the notable exception of Perl, languages "scope" variables to the subroutine / procedure / method / proc / macro in which they are defined, unless you take other specific action such as declaring them global.

This piece of Python code - a rather messy example which resulted from a practical demonstration earlier today - shows examples of many facets of variable sharing to defined functions, and a couple of surprises too! """

# This first is a variable in the main code only.
# There is a different first in the function "one"
 
# second is in the main code
# As it is used READ ONLY in the function, it is shared there
 
first = 1
second = 14
 
def one():
   first = 4 + second
   first *= 2
   print first
   result = first+3
# Referring to a variable in the functions own name space
# is broadly equivalent to it being "static" - it is visible
# outside, and retained for next time the function is called
   one.latest = result
   return result, first, second
 
# A Lambda is a quick way of defining a function
two = lambda john: john + 2
# A function is an object, so you can easily give
# it another reference (i.e. a second name!)
three = two
 
print first
# A function returns one object - but if that object is a
# tuple, then it can be saved as multiple variables (objects)
zig, zag, zog = one()
print zig
print zag
print zog
 
print first
print second
 
# Swapping over two values in Python
# No need for a temporary variable
# (or rather - Python provides the temporary tuple!)
first, second = second, first
 
print first
print second
 
dis = two(first)
print dis
 
dat = three(dis)
print dat
 
print one.latest
 
""" Here are the results if running that!
1
36
39
36
14
1
14
14
1
16
18
39
"""


""" Using the ''' notation, the whole of this article is a working Python program which you can simply cut and paste and run for yourself!"""