Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.
-John Woods comp.lang.c++
(also the preface to Idiomatic Python)
Exceptions are everywhere in Python, even in a for
loop!
for
loops use them for stopping.
When you use for
, iter()
is called on it and it goes through it until StopIteration
is raised.
my_list = ['exceptions', 'are', 'cool']
a = iter(my_list)
a.next()
a.next()
a.next()
a.next()
Use them to write EAFP vs LBYL code!
Bad:
def get_log_level(config_dict):
if 'ENABLE_LOGGING' in config_dict:
if config_dict['ENABLE_LOGGING'] != True:
return None
elif not 'DEFAULT_LOG_LEVEL' in config_dict:
return None
else:
return config_dict['DEFAULT_LOG_LEVEL']
else:
return None
Good:
def get_log_level(config_dict):
try:
if config_dict['ENABLE_LOGGING']:
return config_dict['DEFAULT_LOG_LEVEL']
except KeyError:
# if either value wasn't present, a
# KeyError will be raised, so
# return None
return None
*
operator to represent the "rest" of a listmy_list = ['I', 'want', 'a', 'big', 'sandwich']
Try these:
(*uno, dos, tres) = my_list
>>> ?
(uno, *dos, tres) = my_list
>>> ?
(uno, dos, *tres) = my_list
>>> ?
dict
comprehensionEveryone knows about list comprehensions, but what about dict comprehensions?
This is super useful for filtering information.
class User:
def __init__(self, first_name, last_name, email, credits):
self.first_name = first_name
self.last_name = last_name
self.email = email
self.credits = credits
users_list = [
User('Luis', 'Pugoy', '[email protected]', 69),
User('Marte', 'Parte', '[email protected]', 80085),
User('Gibby', 'Duenas', None, 666),
User('Janine', 'Duenas', '[email protected]', 10000)
]
emails = {user.first_name: user.email for user in users_list if user.email}
set
comprehension...how about set comprehensions?
class User:
def __init__(self, first_name, last_name, email, credits):
self.first_name = first_name
self.last_name = last_name
self.email = email
self.credits = credits
users_list = [
User('Luis', 'Pugoy', '[email protected]', 69),
User('Marte', 'Parte', '[email protected]', 80085),
User('Gibby', 'Duenas', None, 666),
User('Janine', 'Duenas', '[email protected]', 10000)
]
unique_fams = {user.last_name for user in users_list if user.credits > 100}
namedtuple
Is it a tuple
is it a dict
? No, it's a namedtuple
!
What is it?
Let's rewrite User
class!
from collections import namedtuple
User = namedtuple('User', ['first_name', 'last_name', 'email', 'credits'])
gibby = User('Gibby', 'Duenas', None, 666)
# You can get attributes it by position
print gibby[0]
# Or by name
print gibby.last_name
# But like a tuple, it's immutable. This gives an error
gibby.last_name = 'McGibberson'
for a, b in ((user.last_name.upper(), 'Php ' +
str(user.credits)) for user in users_list):
print a, b
_
denotes protected__
denotes privateNope!
_
makes sure it's not imported with *
__
"mangles", useful when someone else will use your class as superclass and you wanna protect your class's variables.__enter__
and __exit__
in your classes that require housekeepingwith
?__enter__
and __exit__
are good for stuff like db connections