Curious function argument
steve+comp.lang.python at pearwood.info
Sat Nov 15 11:39:30 CET 2014
> I saw in a code from a previous message in this forum
> a curious function argument.
> def test(x=):
> print(x) ## Poor man's object
> x += 1
> I understand that the author wants to implement a global
> variable x . It would be better to write 'global x' inside the
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  (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:
x = 0
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:
func = functools.partial(next, gen())
func() # returns 0
func() # returns 1
func() # returns 2
More information about the Python-list