Mutable default values for function parameters

Erik Max Francis max at alcyone.com
Fri Oct 5 13:44:57 EDT 2001


sebastien wrote:

> In fact my question is maybe not related to mutable default arguments
> at all. This is only the way I used to try to solve my problem wich is
> to find a way to mimic this:
> 
> def variant(data, old_data):
>         r = (data <> old_data[0])
>         old_data[0] = data
>         return r
> 
> A=[None]
> for i in range(10):
>         assert variant(i,A)
> 
> But without mandate the user to explicitely manage the plumbery used
> to save the data between two calls of the function (A here).

Why not make the interface clearer and have a support class that holds
one value and supports get and set methods and have the caller pass that
in?  That would make things much clearer and everyone would agree on the
interface.

	class Placeholder:
	    def __init__(self, x = None):
	        self.x = x

	    def get(self): return self.x
	    def set(self, x): self.x = x

	def variant(data, oldData):
	    r = data != oldData.get()
	    oldData.set(data)
	    return r

	A = Placeholder()
	for i in range(10):
	    assert variant(i, A)

The contract is enforced since if the caller pass in something without
get and set methods AttributeErrors will be thrown (or you could
explicitly enforce the type of oldData with a typecheck).

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ Morality is a weakness of the mind.
\__/ Arthur Rimbaud
    Alcyone Systems' CatCam / http://www.catcam.com/
 What do your pets do all day while you're at work?  Find out.



More information about the Python-list mailing list