4

I am running a Pylons project and ran into this strange problem. When submitting a form i have an option to add a logo (simple .png). The logo is passed in a FieldStorage instance. I try to evaluate if the logo was sent with this:

if request.params.get('logo'):
    do x

However, that always evaluates to False, even when there is logo. If I print request.params I get UnicodeMultiDict([('logo', FieldStorage('logo', u'tux.png'))]).

I solved it with:

if not request.params.get('logo') == None:
    do x

I fail to see why that works and the first example does not.

datacarl
  • 2,591
  • 25
  • 21
  • What does `bool(FieldStorage('logo', u'tux.png'))` return? – Fred Foo Feb 17 '12 at 11:45
  • 1
    This doesn't answer your question, but according to pep8 you should use "is None" instead of "== None". See here for more info: http://stackoverflow.com/q/100732/1205715 – jbowes Feb 17 '12 at 11:53

2 Answers2

5

This is interesting, somehow the FieldStorage object resolves to false.

It is perfectly legal to write the following (a bit easier):

if request.params.get('logo') is not None:
    # do x
Constantinius
  • 34,183
  • 8
  • 77
  • 85
3

With request.params.get('logo') you're getting a FieldStorage object, which probably evaluates to False, no matter what.

Anyway, you're just testing for existance of the 'logo' key in the dictionary. Why don't you use dictionary semantics for that? Haven't checked, but I guess it supports something like:

if 'logo' in request.params:
    do x

Edit: had a look to the code. UnicodeMultiDict is a subclass from UserDict.DictMixin, so it implements __contains__ and supports what I suggested.

Ricardo Cárdenes
  • 9,004
  • 1
  • 21
  • 34
  • Yes, that works fine as well. Still, I cannot see the logic in FieldStorage evaluating to False. – datacarl Feb 17 '12 at 12:45
  • Go figure. `FieldStorage` is meant to be a general purpose storage, though, and as long as there's no defined behaviour for it when evaluating into a boolean, I there's no need for it to follow a certain logic. – Ricardo Cárdenes Feb 17 '12 at 14:17