Skip to content

Instantly share code, notes, and snippets.

@mikhail
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikhail/32715d3a0eca5f5ee368 to your computer and use it in GitHub Desktop.
Save mikhail/32715d3a0eca5f5ee368 to your computer and use it in GitHub Desktop.
Python: variable scope

Python's scope

Python's scope of variables should be intuitive, but for those that don't find it as such here's a quick example.

In the file below scope.py I create a dummy class Temp() which prints some debug text when its created and destroyed.

$ python scope.py
Initiating quick
Destroying quick
Initiating global
before scope
Initiating in-scope
Destroying in-scope
after scope
Destroying global
# This class will show debug info when instantiated and destroyed
class Temp(object):
def __init__(self, name):
self._name = name
print 'Initiating %s' % self._name
def __del__(self):
print 'Destroying %s' % self._name
# The following code will provide a good example of scope.
def scope():
t = Temp('in-scope')
Temp('quick') # Not assigned to a variable
t = Temp('global') # Saved until further use
print 'before scope'
scope()
print 'after scope'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment