Tag: Python
-
-
Crimes with Python's Pattern Matching
-
Two workers are quadratically better than one
-
Property Testing with Complex Inputs
-
The Hard Part of Learning a Language
-
How fast do I talk?
-
Python Negatypes
-
Finding Property Tests
-
Property Tests + Contracts = Integration Tests
-
Introduction to Contract Programming
-
Instructive and Persuasive Examples
-
Hypothesis Testing with Oracle Functions
-
Doctests in Python
-
Hate Your Tools
Context Managers for Debugging (Python)
A small helper I use to debug some python programs:
from contextlib import contextmanager
@contextmanager
def debug_error():
try:
yield
except Exception as e:
breakpoint()
quit()
### usage
with debug_error():
x = 1
y = 0
x/y # x and y will be avail in pdb
You can also put things before the yield
(which will run before the with
block), and after it (to run at the end of the block.) Anything put after it will run at the end of the block. See @contextmanager for more info.
Notes
Path Objects (Python)
Python 3.4 added path objects, but most people still don’t know about them. They simplify a lot of file operations:
### Without pathlib
path = "path/to/file"
# parent dir
os.path.dirname(path)
# file suffix
os.path.splitext(path)[1]
# read file
with open(path) as f:
x = f.read()
### With pathlib
path = pathlib.Path("path/to/file")
# parent dir
path.parent
# file suffix
path.suffix
# read file
x = path.read_text()
Paths are also OS-independent, so the same code will generally work on both Windows and Unix.