[Zope-dev] Re: Parameter referencing bug in Python Scripts?
Tres Seaver
tseaver at zope.com
Mon Mar 22 11:09:29 EST 2004
Brian Brinegar wrote:
> Hmmm,
>
> There seems to be a bug in the way parameters are referenced in python
> scripts. I have a simple script that has a list as a default parameter.
> The script then appends something to this list and returns the list.
> Each time I call the script the list gets to be one element longer. Here
> is an example script:
>
> ## Script (Python) "pyFix"
> ##bind container=container
> ##bind context=context
> ##bind namespace=
> ##bind script=script
> ##bind subpath=traverse_subpath
> ##parameters=a=['a']
> ##title=
> ##
> a.append('b')
> return a
>
> The output from the script is as follows:
> 1st call: ['a','b']
> 2nd call: ['a','b','b']
> 3rd call: ['a','b','b','b']
> 4th call: ['a','b','b','b','b']
> etc.
>
> It seems that I'm getting a reference to the default parameter which I
> then modify for future calls. Currently I'm getting around this by
> having list parameters default to none and then setting the defaults
> within the script.
>
> I have some security concerns since I can change the default parameters
> for other users on the server. Or so it seems.
>
> Suggestions?
The behavior you are observing is not unique to PythonScripts; mutable
default values are a notorious bug magnet for Python applications in
general. Try the following in your Python interpreter:
>>> def memoize(value, seen=[]):
... seen.append(value)
... return seen
...
>>> memoize('a')
['a']
>>> memoize('b')
['a', 'b']
>>> memoize('b')
['a', 'b', 'b']
The classic advice here is, "Don't do that." Instead, use a non-mutable
default value (e.g. None or the empty tuple), and special case it. Even
better, avoid writing to the default, e.g.,::
## Script (Python) "pyFix"
##parameters=a=('a',)
##
result.extend(a)
result.append('b')
return result
Tres.
--
===============================================================
Tres Seaver tseaver at zope.com
Zope Corporation "Zope Dealers" http://www.zope.com
More information about the Zope-Dev
mailing list