zen-of-python

raise statement on a conditional expression

心已入冬 提交于 2019-11-29 10:59:50
问题 Following "Samurai principle", I'm trying to do this on my functions but seems it's wrong... return <value> if <bool> else raise <exception> Is there any other "beautiful" way to do this? Thanks 回答1: Inline/ternary if is an expression, not a statement. Your attempt means "if bool, return value, else return the result of raise expression " - which is nonsense of course, because raise exception is itself a statement not an expression. There's no way to do this inline, and you shouldn't want to.

How to print to stderr in Python?

放肆的年华 提交于 2019-11-26 01:09:59
问题 There are several ways to write to stderr: # Note: this first one does not work in Python 3 print >> sys.stderr, \"spam\" sys.stderr.write(\"spam\\n\") os.write(2, b\"spam\\n\") from __future__ import print_function print(\"spam\", file=sys.stderr) That seems to contradict zen of Python #13 † , so what\'s the difference here and are there any advantages or disadvantages to one way or the other? Which way should be used? † There should be one — and preferably only one — obvious way to do it.