12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

...>>> selector( )99Remember, though, that this means the assignment also changes the global X, not alocal X. Within a function, you can’t use both local and global versions of the samesimple name. If you really meant to print the global, and then set a local of the samename, import the enclosing module, and use module attribute notation to get to theglobal version:>>> X = 99>>> def selector( ):... import _ _main_ _ # Import enclosing module... print _ _main_ _.X # Qualify to get to global version of name... X = 88 # Unqualified X classified as local... print X # Prints local version of name...>>> selector( )9988Qualification (the .X part) fetches a value from a namespace object. The interactivenamespace is a module called _ _main_ _, so_ _main_ _.X reaches the global version ofX. If that isn’t clear, check out Part V. *Defaults and Mutable ObjectsDefault argument values are evaluated and saved when a def statement is run, notwhen the resulting function is called. Internally, <strong>Python</strong> saves one object per defaultargument attached to the function itself.That’s usually what you want—because defaults are evaluated at def time, it lets yousave values from the enclosing scope, if needed. But because a default retains anobject between calls, you have to be careful about changing mutable defaults. Forinstance, the following function uses an empty list as a default value, and thenchanges it in-place each time the function is called:>>> def saver(x=[]): # Saves away a list object... x.append(1) # Changes same object each time!... print x...>>> saver([2]) # Default not used[2, 1]>>> saver( ) # Default used[1]>>> saver( ) # Grows on each call![1, 1]* <strong>Python</strong> has improved on this story somewhat by issuing for this case the more specific “unbound local” errormessage shown in the example listing (it used to simply raise a generic name error); this gotcha is still presentin general, though.Function Gotchas | 373

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

Saved successfully!

Ooh no, something went wrong!