Understanding Mutability
00:00 Understanding How Mutability Affects Global Variables Python has mutable and immutable data types. Mutable types such as lists and dictionaries allow you to change or mutate their values in place.
00:15 By contrast, immutable types such as numbers, strings, and tuples, don’t allow you to modify their values in place. To quickly illustrate how mutability and immutability work in Python, consider the example on screen where you mutate a list in place changing the value of its elements or items.
00:42 Here you mutate the value of numbers. Because Python lists are mutable objects, this mutation doesn’t change the identity of the list object, only its value.
00:53
You can confirm this by comparing the output of the built-in id()
function before and after the mutations. But what happens if you try to perform a similar action on an immutable data type, such as a tuple?
01:11
The tuple is storing letters. Python tuples are immutable, so you can’t change their items in place as you did with the list of numbers. When you try it, you get a TypeError
.
01:25 When it comes to using global variables that point to mutable objects inside your functions, you’ll note that it’s possible to change their values in place directly.
01:35 For example, let’s say you are creating a REST API application. For convenience, you use a global dictionary to share the API configurations across the application’s code.
01:47 For further convenience, you write a short function that allows your code to update the configuration parameters.
02:06
Here, the update_config
function allows you to update the app’s configuration. The function takes keyword-only arguments. Each argument must be a valid configuration parameter with its corresponding value.
02:20
You check this condition with the in
operator in a conditional statement.
02:29
If the parameter is invalid, then the function raises a KeyError
. Because Python dictionaries are mutable data types, you can change the values of the config in place from within update_config
without using global
or globals()
.
02:45
You can even add new key-value pairs if they’re valid configuration parameters. For example, the first call to update_config
adds the API key parameter, while the second call updates the timeout parameter.
03:01 It’s important to remember that configurations and settings are often an important part of an app or system’s global state. Changing a configuration while that system is running mutates its global state.
03:14 You should only make this type of change if you’re being very careful. Some apps and software systems ask for a restart or reload after you change some of their configuration parameters, and that’s a good way to deal with this kind of state mutation.
03:30 In the next section of the course, you’ll see how you can create global variables from inside a function.
Become a Member to join the conversation.