00:00 Now that you’ve seen how pass by reference works and some of its advantages and understand now how Python passes arguments, you’re ready to see how to write Pythonic code to implement some of those benefits. But before we look at best practices, let’s take a look at a worst practice and why you should avoid it.
00:20 That’s the practice of writing functions with the intent to modify global variables. Short version of the story: it’s generally a bad idea. Not that global variables themselves are bad.
00:33 You can define a global variable by creating it outside of any function. Then, any part of the program can access it. This is very useful for values in your program that won’t change. For example, if you’re writing a GUI for a system with a very specific window size, you would probably want to use global variables to save the width and height of that window. Or if you’re writing a program to simulate motion on Mars, you might want to use a global variable to represent the constant value for gravity. So variables with a global scope are definitely useful, they just shouldn’t be changed. We often refer to these as global constants.
But if you want to modify a global variable—and you really shouldn’t want to—you must use the keyword
global to declare it as a global variable in your function so Python will let you change it.
01:25 Since Python doesn’t allow you to pass a variable by reference, some programmers use this as a substitute to allow a function to modify a variable and have that change retained after the function.
01:37 But this isn’t a good idea. Why not? Well, first, it’s just hard to read. When you write a function, all the variables the function will use are typically defined in the function. Recall in the last lesson the variables of local scope.
01:54 Making use of a variable defined elsewhere in your program—in many cases, many lines away from this function—will make it difficult for you and other programmers to understand the use of the variable and the function.
02:08 This will make your project very hard to maintain.
02:12 And some additional problems: The function can’t be generalized to modify other variables. It is very closely tied to that specific global variable. Generally, pass by reference allows you to modify any argument variable you provide. Using a global variable really doesn’t provide that same behavior.
02:34 There’s also a concern with something referred to as thread safety. If you have multiple parts of a program needing to share resources, modifying a global variable in one thread can often have an undesirable effect on another thread depending on that variable’s value.
02:51 So while global constants are very useful, using global variables with the intent to modify them during program execution is not an effective way to replicate pass by reference, and just generally, isn’t a good idea at all.
Become a Member to join the conversation.