Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Scope Best Practices

00:00 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 global and nonlocal keywords. When a function modifies data outside its scope using the global or 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.

00:41 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.

01:01 The function used to append content to the file does not have a file_name parameter and it just uses the global FILE_NAME variable.

01:14 That means 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.

01:41 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.