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.
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.
Become a Member to join the conversation.