Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What effect has a statement like 'var and do_something_with(var)' in Python?

Tags:

python

While looking for some answers in a package source code (colander to be specific) I stumbled upon a string that I cannot comprehend. Also my PyCharm frowns on it with 'statement seems to have no effect'.

Here's the code abstract:

...
for path in e.paths():
    keyparts = []
    msgs = []
    for exc in path:
        exc.msg and msgs.extend(exc.messages()) # <-- what is that?
        keyname = exc._keyname()
        keyname and keyparts.append(keyname) # <-- and that
    errors['.'.join(keyparts)] = '; '.join(interpolate(msgs))
return errors
...

It seems to be extremely pythonic and I want to master it!

UPD. So, as I see it's not pythonic at all - readability is harmed for the sake of shorthand.

like image 827
yentsun Avatar asked May 03 '12 23:05

yentsun


1 Answers

If keyname evaluates to False, the and statement will return false immediately and not evaluate the second part. Otherwise, it will evaluate the second part (not that the return value matters in this case). So it's basically equivalent to:

if keyname: 
    keyparts.append(keyname)

I'm not sure that it's very pythonic though, since the the version I just suggested seem much more readable (to me personally, at least).

like image 79
happydave Avatar answered Oct 19 '22 18:10

happydave