Bizarre method keyword-arg bug.

Fredrik Lundh fredrik at pythonware.com
Mon Aug 18 04:51:25 EDT 2008


Jasper wrote:

> I'm stumped.  I'm calling a method that has keyword args, but not
> setting them, and yet one of them starts off with data?!
> 
> The class definition begins like so:
> 
> class BattleIntentionAction( BattleAction ):
>     def __init__( self, factionName, location, tactic='hold',
> targetFacName='', terrainArgs=[], garrisonIds=[] ):
>         self.terrainArgs = terrainArgs
>         print terrainArgs
> 
> The constructor is called somewhere else, like so:
> act = BattleIntentionAction( facName, self.location )
> 
> During this object's construction, terrainArgs is set to a list with
> values corresponding to a previously created BattleIntentionAction!

default argument values are evaluated when the function object is 
created (by the "def" statement, that is), not when the resulting 
function is called.  if you mutate the default values, the mutations 
will stick.

this is explained in the FAQ, the tutorial, and the reference manual, 
and hopefully in your favourite python book as well; see e.g.

    http://docs.python.org/tut/node6.html#SECTION006710000000000000000
    http://docs.python.org/ref/function.html

</F>




More information about the Python-list mailing list