Matt Wilson schrieb:
> On Feb 21, 6:48 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> 
>> How about
>>
>> def f(self, a=[], b=[])
>>
>> Just a guess though. To be brutally honest I'm not sure if there even is
>> a validator invoked in case of no value being present at all. IF so,
>> you could of course create your own ForEach-validator that just does
>> this, overloading the _to_python-method (or whichever is needed, but I
>> guess that's the one) to return an empty list if the
>> super-implementation doesn't.
> 
> I took a stab at making my own validator.  Comments requested:
> 
> class IntegerList(validators.FancyValidator):
>     "Make sure that we get a list of integers back."
> 
>     messages = dict()
> 
>     def _to_python(self, value, state):
>         if value == "empty list": return []
>         elif isinstance(value, list): return [int(x) for x in value]
>         else: return [int(value)]
> 
> Then I changed my f controller to be like this:
> 
>     @validate(validators={'a':IntegerList()},
>                           'b':IntegerList()})
>     @expose()
>     def f(self, a="empty list", b="empty list"):
>         log.debug("a is %s." % a)
>         log.debug("b is %s." % b)
>         return dict(a=a, b=b)
> 
> Everything seems to work OK.
> 
> I don't like the idea of putting the empty lists into the method
> definition.  I've had bad luck with that in the past when python would
> create a single list and keep it across function calls, like this:

Of course you need to be careful when using mutables as default 
arguments. But your solution is worse - how do you distinguish between 
"no argument passed" and "empty list" passed?

Usually, if one wants what you are after - getting a list in all 
circumstances - the code then is supposed to look like this:

def foo(a):

    for value in a:
      ...


without a preliminary check. In that case, you might as well use

def foo(a=()):

The empty tuple is immutable.

However, I'm a bit flabbergasted that the default-argument you pass to a 
and b somewhow is really used in the validator. If that's the case, it 
means that the validate-decorator somehow inspects the method signature.

Might that be as it is, IF things work that way, you are still better 
off with a "None" there - which is also an immutable, and a much safer 
value to use because it can't collide with a possible user-input. Think 
of the same problem as yours, but without the int()-requirement. Then 
entering "empty list" would be forbidden for your user.

Diez

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"TurboGears" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/turbogears?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to