Python Workout: 50 ten-minute exercises by Reuven M. Lerner

Python Workout: 50 ten-minute exercises by Reuven M. Lerner

Author:Reuven M. Lerner [Lerner, Reuven M.]
Language: eng
Format: epub
Publisher: Manning Publications Co.
Published: 0101-01-01T00:00:00+00:00


Figure 6.2 Inner vs. outer x

The global statement

What if, from within the function, I want to change the global variable? That requires the use of the global declaration, which tells Python that you’re not interested in creating a local variable in this function. Rather, any retrievals or assignments should affect the global variable; for example

x = 100 def foo(): global x x = 200 print(x) print(x) foo() print(x)

This code will print 100, 200, and then 200, because there’s only one x, thanks to the global declaration.

Now, changing global variables from within a function is almost always a bad idea. And yet, there are rare times when it’s necessary. For example, you might need to update a configuration parameter that’s set as a global variable.

Enclosing

Finally, let’s consider inner functions via the following code:

def foo(x): def bar(y): return x * y return bar f = foo(10) print(f(20))

Already, this code seems a bit weird. What are we doing defining bar inside of foo? This inner function, sometimes known as a closure, is a function that’s defined when foo is executed. Indeed, every time that we run foo, we get a new function named bar back. But of course, the name bar is a local variable inside of foo; we can call the returned function whatever we want.

When we run the code, the result is 200. It makes sense that when we invoke f, we’re executing bar, which was returned by foo. And we can understand how bar has access to y, since it’s a local variable. But what about x? How does the function bar have access to x, a local variable in foo?

The answer, of course, is LEGB:

First, Python looks for x locally, in the local function bar.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.