Curious function argument

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Nov 15 11:39:30 CET 2014


ast wrote:

> Hello
> 
> I saw in a code from a previous message in this forum
> a curious function argument.
> 
> def test(x=[0]):
>    print(x[0])   ## Poor man's object
>    x[0] += 1
> 
>>>> test()
> 0
>>>> test()
> 1
>>>> test()
> 2
>>>> 
> 
> I understand that the author wants to implement a global
> variable x . It would be better to write 'global x' inside the
> function.

No, it's not a global. A better description is that it is a way of faking
static storage for a function: the function test has a "static variable" x
which is independent of any other function's x, but it can remember its
value from one function call to another.


> 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.
> 
> Is it a usual way to implement a global variable ?

No, it's unusual. If you actually want a global, use the global keyword.
Otherwise, there are often better ways to get a similar effect, such as
using a generator:

def gen():
    x = 0
    while True:
        yield x
        x += 1

it = gen()
next(it)  # returns 0
next(it)  # returns 1
next(it)  # returns 2

You can turn that into functional form like this:

import functools
func = functools.partial(next, gen())
func()  # returns 0
func()  # returns 1
func()  # returns 2



-- 
Steven




More information about the Python-list mailing list