用代码说话。
-
-
Save xxleyi/8547c07b0ab63f33c0defe85069ef45b to your computer and use it in GitHub Desktop.
EAFP vs. LBYL
It's easier to ask forgiveness than permission
Look before you leap
Generally EAFP is preferred, but not always.
- Duck typing
If it walks like a duck, and talks like a duck, and looks like a duck: it's a duck. (Goose? Close enough.)
- Exceptions
Use coercion if an object must be a particular type. If x
must be a string for your code to work, why not call
str(x)
instead of trying something like
isinstance(x, str)
EAFP try/except
Example
You can wrap exception-prone code in a try/except
block to catch the errors, and you will probably end up with a solution that's much more general than if you had tried to anticipate every possibility.
try:
return str(x)
except TypeError:
...
Note: Always specify the exceptions to catch. Never use bare except
clauses. Bare except
clauses will catch unexpected exceptions, making your code exceedingly difficult to debug.
Moral: don't use wild-card imports!
Packages
package/
__init__.py
module1.py
subpackage/
__init__.py
module2.py
Simple is Better Than Complex
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
—Brian W. Kernighan, co-author of The C Programming Language and the "K" in "AWK"
In other words, keep your programs simple!
Rule of thumb:
Here's a recent example I saw at work.
➔
We needed a dictionary mapping month numbers (both as string and as integers) to month codes for futures contracts. It can be done in one logical line of code.
➔
The way this works is as follows:
dict()
built-in takes a list of key/value pairs (2-tuples).int()
andstr()
functions to do this for us, and loop over them.Recent example:
month_codes
result: