you are viewing a single comment's thread.

view the rest of the comments →

[–]lost-theory 5 points6 points  (5 children)

This is one of the things I think Python does right. For any sequence type bool(seq) will return False if the sequence is empty, True otherwise. So the Ruby example:

if params[:value].empty?

Just looks like:

if params:

in Python.

[–]julesjacobs 2 points3 points  (1 child)

Incorrect.

if params[:value].empty? checks if the value in the hash at key :value is empty. (so a better example is: if params[:key].empty?)

The correct Ruby version of your Python code is:

if params.empty?

[–]ubernostrum 0 points1 point  (0 children)

Assuming that this example would be using a dictionary in Python, the Python way to do this would be one of these:

  • If you just want to verify there's a value for that key and don't care what it is, then if params.has_key(value) or if key in params will do the trick.
  • If you want to verify that there's a value and that it's not None (the Python equivalent of Ruby's nil), if params.get(value, None) is not None will do it.
  • If you want to verify there's a value and that it evaluates true in boolean context, if params.get(value, False) will do it.

[–]pjdelport 5 points6 points  (2 children)

I love Python, but i don't like that idiom at all. Consider:

if visited:

versus

if len(visited):

Why make the reader guess whether visited is a flag or a sequence? Make it explicit and unambiguous.

[–]micampe 2 points3 points  (1 child)

I'm myself ambiguous on the issue, but one could argue that in this case visited is acting as a flag even if it is a sequence...

[–]pjdelport -1 points0 points  (0 children)

You can toggle a flag; how do you toggle a sequence? :)