12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Functions can similarly hide global variables of the same name with locals:X = 88def func( ):X = 99# Global X# Local X: hides globalfunc( )print X# Prints 88: unchangedHere, the assignment within the function creates a local X that is a completely differentvariable from the global X in the module outside the function. Because of this,there is no way to change a name outside a function without adding a global declarationto the def (as described in the next section).The global StatementThe global statement is the only thing that’s remotely like a declaration statement in<strong>Python</strong>. It’s not a type or size declaration, though; it’s a namespace declaration. Ittells <strong>Python</strong> that a function plans to change one or more global names—i.e., namesthat live in the enclosing module’s scope (namespace). We’ve talked about global inpassing already. Here’s a summary:• Global names are names at the top level of the enclosing module file.• Global names must be declared only if they are assigned in a function.• Global names may be referenced in a function without being declared.The global statement consists of the keyword global, followed by one or morenames separated by commas. All the listed names will be mapped to the enclosingmodule’s scope when assigned or referenced within the function body. For instance:X = 88# Global Xdef func( ):global XX = 99# Global X: outside deffunc( )print X # Prints 99We’ve added a global declaration to the example here, such that the X inside the defnow refers to the X outside the def; they are the same variable this time. Here is aslightly more involved example of global at work:y, z = 1, 2 # Global variables in moduledef all_global( ):global xx = y + z# Declare globals assigned# No need to declare y, z: LEGB rule316 | Chapter 16: Scopes and Arguments

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!