Skip to content

Instantly share code, notes, and snippets.

View sloria's full-sized avatar

Steven Loria sloria

View GitHub Profile
f = open('file.txt', 'w')
f.write('hi')
f.close()
# Better
with open('file.txt', 'w') as f:
f.write('hi')
with pytest.raises(ValueError):
int('hi')
if self.flags & 0b1000: # Am I visible?
...
# Better
...
@property
def is_visible(self):
return self.flags & 0b1000
if self.is_visible:
# Bad
if type(entry) is Film:
responsible = entry.producer
else:
responsible = entry.author
# Shouldn't use type() or isinstance() in conditional --> smelly
# Better
class Film:
class ParagraphEditor:
...
def highlight(self, rectangle):
self.reverse(rectangle)
# Better
class ParagraphEditor:
...
highlight = reverse # More readable, more composable
_DEFAULT_PORT = 1234
class SomeProtocol:
...
def __enter__(self):
self._client = socket()
self._client.connect(
(self.host,
self.port or _DEFAULT_PORT)
)
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
# Sometimes need more flexibility --> use properties
class Point:
def __init__(self, x, y):
self._x, self._y = x, y
# Bad
# Can't change type of collection
# e.g. can't change employees from a list to a set
class Department:
def __init__(self, *employees):
self.employees = employees
for employee in department.employees:
...
# Meh
class Rectangle:
def bottom_right(self):
return Point(self.left + self.width,
self.top + self.height)
# Better to use temporary variables for readability
class Rectangle:
...
def bottom_right(self):
item in a_set
item not in a_set
# a_set <= other
a_set.is_subset(other)
# a_set | other
a_set.union(other)
# a_set & other
obj == obj2
obj1 is obj2
class Book:
...
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return (self.author == other.author and
self.title == other.title)