Skip to content

Instantly share code, notes, and snippets.

View sloria's full-sized avatar

Steven Loria sloria

View GitHub Profile
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)
)
# Better
class Boiler:
def safety_check(self):
if any([self.temperature > MAX_TEMPERATURE,
self.pressure > MAX_PRESSURE]):
if not self.shutdown():
self.alarm()
def alarm(self):
with open(BUZZER_MP3_FILE) as f:
# 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:
# 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):
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')
# Awkward
for options_shortcut in self.options_shortcuts:
options_shortcut.this()
options_shortcut.that()
# Better
for each in self.options_shortcuts:
each.this()
each.that()
~/.ideas.md
# Software
- doomed startup idea 1
- some feature for an open-source project
- doomed startup idea 2
- ...
# Blog posts
- the .ideas file
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
# Instead of this
self.release_water()
self.shutdown()
self.alarm()
class Reactor:
...
def release_water(self):
self.valve.open()
return self