Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #80603
| From | Denis McMahon <denismfmcmahon@gmail.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: Curious function argument |
| Date | 2014-11-12 14:03 +0000 |
| Organization | A noiseless patient Spider |
| Message-ID | <m3vpce$pm6$2@dont-email.me> (permalink) |
| References | <54635bce$0$2384$426a74cc@news.free.fr> |
On Wed, 12 Nov 2014 14:07:14 +0100, ast wrote: [function def with mutable default parameter] > I understand that the author wants to implement a global variable x . It > would be better to write 'global x' inside the function. It may not be the case that the purpose was to implement a global variable, but rather to illustrate what happens when you use a mutable default parameter. > At first test() function call, it prints 0, that's OK. > But at the second call, since we dont pass any argument to test(), x > should be equal to its default value [0] (a single item list). But it > seems that Python keeps the original object whose content has been > changed to 1. This is explained in the docs: https://docs.python.org/3/reference/compound_stmts.html#function- definitions Default parameter values are evaluated from left to right *when the function definition is executed*[1]. This means that the expression is evaluated once, when the function is defined, and that the same “pre- computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. [1] ie when the function is 'compiled', not each time it executes. -- Denis McMahon, denismfmcmahon@gmail.com
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Curious function argument "ast" <nomail@invalid.com> - 2014-11-12 14:07 +0100 Re: Curious function argument Denis McMahon <denismfmcmahon@gmail.com> - 2014-11-12 14:03 +0000 Re: Curious function argument Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2014-11-12 09:18 -0500 Re: Curious function argument Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-11-15 21:39 +1100 Re: Curious function argument Akira Li <4kir4.1i@gmail.com> - 2014-11-28 08:52 +0300
csiph-web