Skip to content

Instantly share code, notes, and snippets.

View sloria's full-sized avatar

Steven Loria sloria

View GitHub Profile
@sloria
sloria / bobp-python.md
Last active March 2, 2024 11:01
A "Best of the Best Practices" (BOBP) guide to developing in Python.
View bobp-python.md

The Best of the Best Practices (BOBP) Guide for Python

A "Best of the Best Practices" (BOBP) guide to developing in Python.

In General

Values

  • "Build tools for others that you want to be built for you." - Kenneth Reitz
  • "Simplicity is alway better than functionality." - Pieter Hintjens
@sloria
sloria / recorder.py
Last active November 8, 2023 10:43
WAV recording functionality using pyaudio
View recorder.py
# -*- coding: utf-8 -*-
'''recorder.py
Provides WAV recording functionality via two approaches:
Blocking mode (record for a set duration):
>>> rec = Recorder(channels=2)
>>> with rec.open('blocking.wav', 'wb') as recfile:
... recfile.record(duration=5.0)
Non-blocking mode (start and stop recording):
View gist:5895737
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
View gist:5895749
# 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:
...
View gist:5895762
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)
View gist:5895766
class Book:
...
def __hash__(self):
return hash(self.author) ^ hash(self.other)
@sloria
sloria / gist:5895768
Last active December 24, 2022 20:04
View gist:5895768
class Book:
...
def __lt__(self, other):
return (self.author, self.title) < (other.author, other.title)
View gist:5895770
class Config:
def __init__(self, **entries):
self.entries = entries
def __add__(self, other):
entries = (self.entries.items() +
other.entries.items())
return Config(**entries)
default_config = Config(color=False, port=8080)
config = default_config + Config(color=True)
@sloria
sloria / dropping_py2.md
Last active August 14, 2022 13:26
Checklist for dropping Python 2 in my libraries
View dropping_py2.md
  • Add pyupgrade to .pre-commit-config.yaml.

If supporting py35, use --py3-plus instead of --py37-plus.

- repo: https://github.com/asottile/pyupgrade
  rev: ...latest version...
  hooks:
  - id: pyupgrade
 args: [--py37-plus]
@sloria
sloria / marshmallow_colander_bench.py
Last active March 26, 2022 19:16 — forked from ergo/marshmallow_colander_bench.py
Comparison between Marshmallow and Colander
View marshmallow_colander_bench.py
import timeit
import uuid
import colander
import marshmallow
class BarList(colander.SequenceSchema):
item = colander.SchemaNode(
colander.Integer(), validator=colander.Range(min=1))