Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

# same as var == None

Do not check if you can, just do it and handle the error

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

Or even better with Python 2.6+:

with open(file_path) as file:

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.

Do not check against type

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.

Don't mix spaces and tabs

GoalKicker.com – Python® Notes for Professionals 764

You might also like