Function Arguments and Parameter Variables
00:00 In this lesson, you’ll explore the relationship between function arguments and parameter variables. In Python, parameter variables are considered local variables, meaning they have local scope. The name only has meaning inside the function.
When you call the function
locals(), it will return the dictionary of all of the local variables and their bindings and whatever has local scope at the place the function was called.
You can also get the dictionary of everything in global scope using the
globals() function. To see how it works, you can create a small function that creates a local variable and calls the
locals() function. I’ll just do this interactively.
00:43 We define our function, create a local variable, give it a value, bind it to an object,
00:55 and then print the locals dictionary.
If I call that function, I can see one single local variable,
my_local, bound to the object
True. Let’s modify this so that this function takes an argument.
So, create the
my_local local variable, and again, print the locals dictionary. This time, I must provide an argument to pass to
Notice here, the parameter name
'my_arg' is in the dictionary, just like the other local variable, and it’s been bound to the object
01:46 Remember, parameter names are bound to the objects passed as arguments on function entry in Python. And again, to illustrate one more time that as arguments are passed to functions parameters create additional references to the object passed, you can write a similar function to track reference counts instead of bindings.
We use the
getrefcount() function again from
02:18 We’ll pass one argument to it—mainly, the one whose references we wish to count. And we will get the reference count for that object passed. First, let’s just get the reference count for the object I’m going to use, but before we actually use it as an argument to the function.
02:42 Since we’re in a REPL, there aren’t all the internal references to the object as there are when running the program from a script, so we only see two references here.
But when I use
"my_value" as the argument to the
show_refcount() function, we will see the additional references created passing that argument to the function parameter
So now you’ve seen when an argument is passed to a function, the parameter name is bound to the same object. You can see that binding in the locals dictionary and you can see the additional reference to it using
03:27 Now you’re ready to see some best practices to replicate in Python how other languages use pass by reference.
Become a Member to join the conversation.