Chapter 18. Arguments
ChapterÂ 17 explored the details behind Pythonâs scopesâthe places where variables are defined and looked up. As we learned, the place where a name is defined in our code determines much of its meaning. This chapter continues the function story by studying the concepts in Python argument passingâthe way that objects are sent to functions as inputs. As weâll see, arguments (a.k.a. parameters) are assigned to names in a function, but they have more to do with object references than with variable scopes. Weâll also find that Python provides extra tools, such as keywords, defaults, and arbitrary argument collectors and extractors that allow for wide flexibility in the way arguments are sent to a function, and weâll put them to work in examples.
Earlier in this part of the book, I noted that arguments are passed by assignment. This has a few ramifications that arenât always obvious to newcomers, which Iâll expand on in this section. Here is a rundown of the key points in passing arguments to functions:
Arguments are passed by automatically assigning objects to local variable names. Function argumentsâreferences to (possibly) shared objects sent by the callerâare just another instance of Python assignment at work. Because references are implemented as pointers, all arguments are, in effect, passed by pointer. Objects passed as arguments are never automatically copied.
Assigning to argument names inside a function does not affect ...
Get Learning Python, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.