11

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.

14
  • 1
    +1 - this is a good question, that's really weird and I have no idea why one would do it. I would argue it isn't Pythonic at all however - readability is one of the most important things in Python, and if you look at it and ask 'why do that', it's not Pythonic. Commented May 3, 2012 at 23:02
  • @Lattyware I agree about a serious readabilty issue with that, was mostly joking about pytonic:)
    – yentsun
    Commented May 3, 2012 at 23:07
  • @Lattyware: If you're asking because you don't know how and and or work it's not a reflection on its Pythonicness. Using and as a guard is very Pythonic. Commented May 4, 2012 at 17:08
  • 1
    @EthanFurman I understand how and and or work in Python, but I've never been a fan of using stuff like that in this kind of way. It has the potential for bugs and is harder to read. Using an if statement is always a better solution. Commented May 4, 2012 at 17:36
  • 1
    @Lattyware: I know you do, I don't think yentsun did; I find it very easy to read (although complex statements should be broken out); careful of using always, as always rarely is. ;) Commented May 4, 2012 at 19:08

3 Answers 3

15

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).

3
  • 3
    Agreed. OP's example violates "explicit is better than implicit" for no good reason.
    – Marcin
    Commented May 3, 2012 at 23:06
  • Second example is invalid syntax on python2 and python3. don't do that. Commented May 3, 2012 at 23:07
  • Thanks - its clear now. I was close to that idea but just couldnt absolutely define what was going on.
    – yentsun
    Commented May 3, 2012 at 23:12
3

and and or are short-circuiting logical operators; which means as soon as Python knows what the answer must be, it stops evaluating any remaining clauses.

In the snippet you posted and is being used to guard the .extend() and .append() functions -- presumably the author does not want to post, for example, None into the lists.

I typically use this feature in if statements:

if name and name[0] in ('Mr', 'Mrs', 'Ms'):
    ...

name is a possibly empty list -- if it is empty, name[0] will fail with an IndexError, so I guard it with name and -- if name is empty, name[0] (and the if block) do not execute and the error is avoided.

This is a very Pythonic feature.

3
  • If name has one element in your example, you're in trouble. name[0] would make the example more obviously correct.
    – happydave
    Commented May 4, 2012 at 17:22
  • @happydave, Good point, thanks. In the original snippet name would always have at least two elements if it existed at all, but that was not apparent when taken out of context. Commented May 4, 2012 at 17:26
  • 1
    @EthanFurman +1 for the link and explaining the reason behind that structure. Also I like that its called 'to guard' - now I know how to address it at least. In your example though, I see more sense in using the guard, because you have 'if'. But the original example a and b.method() has bad readability and a pure trap for newcomers (I can imagine how mature pythonists love it:)
    – yentsun
    Commented May 4, 2012 at 17:43
2

Since in python the first expression in an and statement is evaluated before the second and the interpreter breaks out of evaluating the and statement if the first expression is False,

keyname and keyparts.append(keyname)

is equivalent to:

if keyname:
    keyparts.append(keyname)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.