A "Best of the Best Practices" (BOBP) guide to developing in Python.
- "Build tools for others that you want to be built for you." - Kenneth Reitz
- "Simplicity is alway better than functionality." - Pieter Hintjens
| # -*- 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): |
| # Even better | |
| def lazy_property(fn): | |
| '''Decorator that makes a property lazy-evaluated. | |
| ''' | |
| attr_name = '_lazy_' + fn.__name__ | |
| @property | |
| def _lazy_property(self): | |
| if not hasattr(self, attr_name): |
| {"lastUpload":"2021-08-17T14:10:13.842Z","extensionVersion":"v3.4.3"} |
| 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: | |
| ... | |
| 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) |
| class Book: | |
| ... | |
| def __hash__(self): | |
| return hash(self.author) ^ hash(self.other) |
| class Book: | |
| ... | |
| def __lt__(self, other): | |
| return (self.author, self.title) < (other.author, other.title) |
| 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) |