Professional Documents
Culture Documents
789 PDFsam PythonNotesForProfessionals
789 PDFsam PythonNotesForProfessionals
Pythonistas usually say "It's easier to ask for forgiveness than permission".
Don't:
if os.path.isfile(file_path):
file = open(file_path)
else:
# do something
Do:
try:
file = open(file_path)
except OSError as e:
# do something
It is much better because it is much more generic. You can apply try/except to almost anything. You don't need to
care about what to do to prevent it, just care about the error you are risking.
Python is dynamically typed, therefore checking for type makes you lose flexibility. Instead, use duck typing by
checking behavior. If you expect a string in a function, then use str() to convert any object to a string. If you expect
a list, use list() to convert any iterable to a list.
Don't:
def foo(name):
if isinstance(name, str):
print(name.lower())
def bar(listing):
if isinstance(listing, list):
listing.extend((1, 2, 3))
return ", ".join(listing)
Do:
def foo(name) :
print(str(name).lower())
def bar(listing) :
l = list(listing)
l.extend((1, 2, 3))
return ", ".join(l)
Using the last way, foo will accept any object. bar will accept strings, tuples, sets, lists and much more. Cheap DRY.