Does Python.get () not evaluate True even if there is an object?

I am running a Pylons project and have encountered this strange problem. When submitting the form, I have the opportunity to add a logo (simple .png). The logo is passed in the FieldStorage instance. I am trying to evaluate if a logo was sent with this:

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

However, this is always False, even if there is a logo. If I print request.params, I get UnicodeMultiDict([('logo', FieldStorage('logo', u'tux.png'))]) .

I solved this with:

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

I do not understand why this works, but in the first example this is not.

+4
source share
2 answers

This is interesting, somehow the FieldStorage object resolves false.

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

 if request.params.get('logo') is not None: # do x 
+5
source

With request.params.get('logo') you get a FieldStorage object, which is probably evaluated as False , no matter what.

In any case, you simply check for the presence of the 'logo' key in the dictionary. Why do not you use the semantics of the word for this? Not tested, but I think it supports something like:

 if 'logo' in request.params: do x 

Edit: looked at the code. UnicodeMultiDict is a subclass of UserDict.DictMixin , so it implements __contains__ and supports what I suggested.

+3
source

Source: https://habr.com/ru/post/1397021/


All Articles