Re: Dangerous if_missing in ForEach

Ian Bicking <[email protected]> Wed, 10 Sep 2008 11:14:22 -0500
Newsgroups gmane.comp.python.formencode
Message-ID <[email protected]>
Felix Schwarz wrote:
> Hi,
> 
> I was bitten by a formencode default just some minutes ago so I
> thought that sharing my experience may help others to avoid this
> trap:
> If use you ForEach but the key is not present in your input
> dictionary, you will get an empty list ([]) by default. This is
> somewhat dangerous because the list instance is a mutable object.
> 
> So if your program modifies the resulting list AND your process
> lives longer than just one request, you will get the old list
> instance next time.
> 
> This example will show you the problem:
> # -----------------------------------------
> from formencode import ForEach, Schema
> from formencode.validators import Int
> 
> class Foo(Schema):
>       baz = ForEach(Int)
> 
> schema = Foo()
> fields = schema.to_python({})
> fields["baz"].append(1)
> print schema.to_python({})
> # -----------------------------------------
> 
> Yes, I agree you probably should not modify the result dict in the
> first place. However, sometimes it may be convenient to do so.
> 
> A solution to this would be to change the default of ForEach to
> "()" (tuple) which is not mutable. Unfortunately, this is a backward
> incompatible change which would break many apps for sure.

I changed it to a property that creates new lists each time, which 
should fix this (r3576).  Thanks for the note.

-- 
Ian Bicking : [email protected] : http://blog.ianbicking.org

-------------------------------------------------------------------------
This SF.Net email is sponsored by the Moblin Your Move Developer's challenge
Build the coolest Linux based applications with Moblin SDK & win great prizes
Grand prize is a trip for two to an Open Source event anywhere in the world
http://moblin-contest.org/redirect.php?banner_id=100&url=/