changeset 9:eaf4ddc3b092

Added section on global variables
author Atul Varma <varmaa@toolness.com>
date Thu, 05 Jun 2008 16:11:22 -0700
parents e260fb2db3e5
children 58662d737f49
files PythonForJsProgrammers.txt
diffstat 1 files changed, 30 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/PythonForJsProgrammers.txt	Thu Jun 05 15:55:15 2008 -0700
+++ b/PythonForJsProgrammers.txt	Thu Jun 05 16:11:22 2008 -0700
@@ -219,6 +219,36 @@
 As in JavaScript, they're first-class citizens and can be passed
 around as parameters to other functions and so forth.
 
+Global Variables
+================
+
+Python, like JavaScript, is lexically scoped when it comes to reading
+variables.
+
+However, Python's scoping rules for assignment to undefined variables
+works opposite to JavaScript's; instead of being global by default,
+variables are local, and there is no analog to ``var`` or ``let``.
+Rather, the ``global`` keyword is used to specify that a variable be
+bound to global instead of local scope:
+
+    >>> a = 1              # Define our global variable.
+    >>> def foo(x):
+    ...     a = x + 1      # 'a' is a new local variable.
+    >>> def bar(x):
+    ...     global a       # Bind 'a' to the global scope.
+    ...     a = x + 1
+    >>> foo(5)
+    >>> a
+    1
+    >>> bar(5)
+    >>> a
+    6
+
+This is for the best: as it's well-known that global variables should
+be used as sparingly as possible, it's better for a language
+interpreter to assume that all new assignments are local unless
+explicitly told otherwise.
+
 Closures
 ========