Scope Best Practices
One of the most famous movie quotes of the 21st century says, “With great power comes great responsibility.” This is no different when using the
nonlocal keywords. When a function modifies data outside its scope using the
nonlocal keyword or by modifying a mutable type in place, it’s considered a side effect, similar to when a function modifies its arguments. Modifying global variables is generally considered unwise—not only for Python, but also in other programming languages.
Consider the following example. The first function takes in some content and an optional
file_name. If the
file_name has a value, then the global variable named
FILE_NAME is modified before writing the content to the file.
The function used to append content to the file does not have a
file_name parameter and it just uses the global
write_initial_content() has a side effect, which is changing the global
FILE_NAME variable. So, when these functions are used in another large module, then debugging why the
file_name is no longer called
"foo.txt" when using the
append_content() function can become a big pain.
In Python, using the
global keyword at least makes it explicit that the function is modifying a global variable. In many languages, a function can modify a global variable just by assignment, without announcing it in any way.
01:57 This can make it very difficult to track down where data is being modified. As with many things, there are good reasons to modify variables out of scope, else the possibility would not exist.
02:12 But most of the time there is a better way, usually with function return values.
02:19 This was the end of this section on modifying variables out of scope.
02:25 In the next and final lesson of this course, we’ll do a summary and a wrap-up.
Become a Member to join the conversation.