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.
Python Idioms [pdf]
31–40 of 128 posts
Re: Python Idioms [pdf]
#32As 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…
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"
TrueRe: Python Idioms [pdf]
#33 (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]
#34Interesting 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.
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]
#35I 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…
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]
#36I 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
Re: Python Idioms [pdf]
#37Interesting 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…
Exactly. It's philosophically different from other languages, but it's standard in Python.
Re: Python Idioms [pdf]
#38As 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.
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]
#39That 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]
#40As 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.
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.