Locked learning resources

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

Unlock This Lesson

Locked learning resources

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

Unlock This Lesson

Deciding When to Use Globals

00:00 Deciding When to Use Global Variables In your programming journey, you’ll find some situations where using a global variable may be appropriate or even necessary.

00:11 For example, you may use global variables to handle configurations and settings. If you have settings that apply to your entire program, then using global variables can be a quick solution that will allow you to access these settings from anywhere in your code.

00:27 Small Utility Scripts If you are writing small scripts to automate parts of your workflow or complete tiny tasks, then using global variables can help you get up and running faster, stopping you from over-engineering your solutions. Caching Data If you need to cache data for performance reasons, then you can take advantage of global variables to store the cache data.

00:52 It’s important to note that you should use global variables sparingly and only when absolutely necessary. If you decide to use global variables in your code, then make sure to document their use, especially noting why you’re relying on them.

01:07 In practice, using global variables in your code may have some drawbacks. For example, global variables can make it difficult to keep track of changes to the variable because you can change the variable from anywhere in the code, generate unwanted side effects because changes to a global variable can impact the behavior of other parts of the code, make your code difficult to test and debug because the behavior and result of your functions will depend on the global variable’s current state, affect your code’s reusability because functions that rely on global variables are tightly coupled to those variables. Cause naming conflicts because you might accidentally reuse a global name in different parts of the code causing unexpected results, break encapsulation because global variables introduce hidden dependencies between different parts of your code

01:56 and make your code hard to refactor because changes in one part of the code can affect other parts.

02:03 While you can take advantage of global variables to solve specific problems, you’ll be better off minimizing their use in your code. If you still need to use them, then you can avoid some of their downsides by making them constants.

02:16 That’s because most of the problems with using global variables come from changing their value during your code’s execution.

02:24 So in the next section of the course, you’ll learn about some commonly-used strategies and techniques to avoid using global variables in your functions.

Become a Member to join the conversation.