Live data from Hacker News

Python Idioms [pdf]

safehammad.com

31–40 of 128 posts

Re: Python Idioms [pdf]

#31

Interesting philosophical points. To me personally, testing for 'truthy' and 'falsy' values, or relying on exceptions rather than checking values in advance, feels like sloppy and imprecise programming. A string being empty or not, or an array having items or not, or a boolean being true or false, are all qualitatively totally different things to me -- and just because Python can treat them the same, doesn't mean a p…

I think part of the reasoning behind the truthy / falsy mechanic is that it's more robust. If, for whatever reason, we did: name = None instead of name = '' Then the second conditional would fail, whereas the first would still be fine.

I've personally run into problems when I don't do exact comparisons with True and False. For example, I've forgotten to return a value in one path of a function/method, and then tried to use the result in an if statement in the style recommended by the OP (e.g. if fcall(): do something). After being bitten several times by this, I always do explicit comparisons.

Re: Python Idioms [pdf]

#32

As an implementor of Hy (a homoiconic lisp frontend to Python) I've found certain Python idioms to be rather infuriating of late. In particular: >>> 0 == False True Which makes the idiom of testing truthiness quite annoying in parsing code such as: def is_digit_char(s): """ Return a parsed integer from 's'.""" try: return int(s) except (ValueError, TypeError): return None Which is harmless enough except that as a pre…

Well, it's not really Python's behaviour, just the behaviour of that type. You can always use your own type:

  class I(int):
    def __nonzero__(self):
      return True

  def is_digit_char(s):
    try:
      return I(s)
    except (ValueError, TypeError):
      return None

  >>> if is_digit_char('0'): print "True"
  True

Re: Python Idioms [pdf]

#33
I would add generator expressions:

    (f(x) for x in list_of_inputs)
Just like a list comprehension, but with (...) rather than [...] and with lazy evaluation.

These are useful when you don't need to evaluate all of the inputs at once but still want to iterate over them at some point later on.

Re: Python Idioms [pdf]

#34

Interesting philosophical points. To me personally, testing for 'truthy' and 'falsy' values, or relying on exceptions rather than checking values in advance, feels like sloppy and imprecise programming. A string being empty or not, or an array having items or not, or a boolean being true or false, are all qualitatively totally different things to me -- and just because Python can treat them the same, doesn't mean a p…

I think part of the reasoning behind the truthy / falsy mechanic is that it's more robust. If, for whatever reason, we did: name = None instead of name = '' Then the second conditional would fail, whereas the first would still be fine.

Checking for empty strings can be done with len(mystring)==0 for this reason. In many other languages this method is standard and recommended practice.

Relying on implicit conversions is just sloppy. What if that variable was never supposed to be None in the first place. Better with an exception than continuing with corrupt data.

Remember another python motto: Explicit is better than implicit.

Re: Python Idioms [pdf]

#35
post #3

I disagree with promoting try / catch. Exceptions like ValueError can really happen almost anywhere, so it is usually better to sanitize your inputs. E.g. something like: try: something = myfunc(d['x']) except ValueError: something = None The programmer's intent is probably to only catch errors in the key lookup d['x'], but if there is some bug in the implementation of myfunc() or any of the functions called by myfun…

Not to counter your point, but I would like to quote from PEP8 here:

Additionally, for all try/except clauses, limit the try clause to the absolute minimum amount of code necessary. Again, this avoids masking bugs.

Yes:

    try:
        value = collection[key]
    except KeyError:
        return key_not_found(key)
    else:
        return handle_value(value)
No:

    try:
        # Too broad!
        return handle_value(collection[key])
    except KeyError:
        # Will also catch KeyError raised by handle_value()
        return key_not_found(key)

Re: Python Idioms [pdf]

#36
post #3

I disagree with promoting try / catch. Exceptions like ValueError can really happen almost anywhere, so it is usually better to sanitize your inputs. E.g. something like: try: something = myfunc(d['x']) except ValueError: something = None The programmer's intent is probably to only catch errors in the key lookup d['x'], but if there is some bug in the implementation of myfunc() or any of the functions called by myfun…

That example would surely be better as: something = myfunc(d['x']) if 'x' in d else None

That looks like perl.

Re: Python Idioms [pdf]

#37

Interesting philosophical points. To me personally, testing for 'truthy' and 'falsy' values, or relying on exceptions rather than checking values in advance, feels like sloppy and imprecise programming. A string being empty or not, or an array having items or not, or a boolean being true or false, are all qualitatively totally different things to me -- and just because Python can treat them the same, doesn't mean a p…

>> It seems to be more of a philosophical difference, not right/wrong.

Exactly. It's philosophically different from other languages, but it's standard in Python.

Re: Python Idioms [pdf]

#38
post #11

As a huge Python fan, I'm ashamed to admit but I don't get the while True: break What's the problem? I supose the use case is while True: # do stuff if some_condition: break What is the alternative? 'while some_condition'? That means we must have the 'some_condition' variable outside of the loop. And if we have multiple exit points it may become a mess.

I think this is more for:

   while True:
     result = do_something()
     if not result: 
        break
rather than:

   result = True
   while result:
      result = do_something()

[[edit apparently tab ret submits, not whatever I was trying to do with the actual editing]]

Re: Python Idioms [pdf]

#39
Alex Martelli gave a nice talk called "Permission or Forgiveness" about the exception handling style recommended by OP: http://pyvideo.org/video/1338/permission-or-forgiveness-0. He has some nice insights into this issue.

That being said, I think there are some situations where you want to check for problems up front (possibly in addition to exception handling). In particular, if you are parsing some data from outside the program, you may want to provide some context about what was wrong. KeyError is not very helpful to your users.

Re: Python Idioms [pdf]

#40
post #11

As a huge Python fan, I'm ashamed to admit but I don't get the while True: break What's the problem? I supose the use case is while True: # do stuff if some_condition: break What is the alternative? 'while some_condition'? That means we must have the 'some_condition' variable outside of the loop. And if we have multiple exit points it may become a mess.

Personally, because I find infinite loops to be a real PITA, I prefer to do:

    for _ in xrange(100000):
        break
    else:
        logging.error("ran into an infinite loop")
unless I really do need an infinite loop for things like event handler loop, which is admittedly quite rare.
Post reply on HN