Idiomatic Python
EAFP > LBYL
Just try to do what you expect to work and handle exceptions later if they occurr - “it’s easier to ask for forgiveness than permission” (EAFP) rather than “look before you leap” (LBYL).
|
|
Other examples
|
|
|
|
Long strings
Use a separate set of parenthesis for each line and wrap them all in a set of parenthesis.
|
|
Generator expression instead of if-else membership testing
|
|
Negated logical operators
Use if x not in y
instead of if not x in y
, since they are semantically identical but the former makes it clear that not in
is a single operator and reads like English. (Idion from PEP8, rationale from Alex Martelli)
Using argparse
There are different ways to use argparse. I usually use
|
|
I use this as my default approach because it’s appropriately simple for my normal use case and it makes testing main()
easy. Alternatively, I sometimes use the below (based on this
discussion)
|
|
Use ast.literal_eval()
instead of eval()
Why? Basically, because eval
is very
dangerous
and would happile evaluate a string like os.system(rm -rf /)
, while
ast.literal_eval
will only evaluate Python
literals.