172 Posts Tagged ‘python’ (Page 2)

(All tags.)


Python: fuss-free use of Homebrew libraries for package dependencies

Some Python packages require native libraries to be installed on your system when you install them. For example, mysqlclient requires libssl and libcrypto. If those libraries are missing at install time, clang, the C compiler, fails with a message like:

Read more...

Python: test for unraisable exceptions with unittest.mock

A few days ago, I blogged about debugging unraisable exceptions with Rich. Here’s a sequel on testing that some block of code doesn’t trigger any unraisable exceptions.

Read more...

Python: debug unraisable exceptions with Rich

Take this Python class:

Read more...

Python: spy for changes with sys.monitoring

Python 3.12 introduced sys.monitoring, a new framework for “monitoring” tools like debuggers and profilers to hook into. It provides fine-grained control so tools can listen only to certain events on specific lines of code. The framework came from PEP 669, thanks to Mark Shannon of the Faster CPython team.

Read more...

Python: create temporary files and directories in unittest

Sometimes, tests need temporary files or directories. You can do this in Python’s unittest with the standard library tempfile module. Let’s look at some recipes to do so within individual tests and setUp().

Read more...

Python: my new uv setup for development

uv is a new, fast Python packaging tool. Since the August 20 update, uv can now manage both versions of Python and Python-powered tools.

Read more...

Python: profile total memory allocated with tracemalloc

tracemalloc is Python’s standard library module for tracking memory allocations. It has many bells and whistles for detailed analysis, allowing you to slice allocations by file and line or compare snapshots. But for simple purposes, displaying the total memory allocated is sufficient, which is what this recipe does:

Read more...

Python: Fail in three characters with 1/0

Here’s a code snippet I often type:

Read more...

Python: Import by string with pkgutil.resolve_name()

Django and other frameworks often allow you to configure classes, functions, or modules to import using strings. To do the same in your own code, use pkgutil.resolve_name() from the standard library (added in Python 3.9):

Read more...

Python: Mock an inner import

Sometimes, you want to test a function that uses an inner import and mock that imported object. For example, say you wanted to mock dig() in this example:

Read more...

Python: Show all subclasses of a class

class.__subclasses__() returns a list of the direct subclasses of a given class:

Read more...

Python: Diffing unit tests to keep a copy-pasted code in sync

Copy-paste-tweaking library code feels like a dirty but inevitable programming practice. Often driven by deadlines or other constraints, it seems all projects end up with something copy-pasted in and tweaked for one specific use case.

Read more...

Python: Make line number paths with inspect

Many terminals and text editors support what I’ll call “line number paths” of the form <filename>:<lineno>. Opening that path, whether by clicking or passing to a CLI, opens the given file at that line.

Read more...

My appearance on The Python Show

Earlier this week, I made another podcast appearance on The Python Show, episode 22: Git and Django with Adam Johnson. As fellow authors, Mike and I talked a lot about the writing process, on topics like:

Read more...

My appearance on the PyBites Podcast

Last week, I made another podcast appearance on the PyBites Podcast, episode 139: Maximizing Your Developer Experience (DX) with Adam Johnson. We talked about various topics, including:

Read more...

My appearance on The Real Python Podcast 179

I had the pleasure of returning to The Real Python podcast in last week’s episode 179, Improving Your Git Developer Experience in Python. It was great to catch up with host Christopher Bailey and chat about:

Read more...

GitHub Actions: Faster Python runs with cached virtual environments

Most projects I work on use Python, good ol’ Pip, and pip-tools. Below is a pattern I’ve used to speed up the GitHub Actions workflow runs on several such projects. On larger projects with many dependencies, it can save tens of seconds per run.

Read more...

Introducing flake8-logging

The Python standard library’s logging module is a go-to for adding observability to applications. Many tools also integrated with it or enhance its capabilities, such as structlog and Sentry.

Read more...

Python: Profile a section of code with cProfile

When trying to improve a slow function or module, it’s always a good idea to profile it. Here’s a snippet for quickly profiling a section of code with Python’s cProfile module, in two flavours. It’s adapted from the cProfile documentation’s Profile example. I have used versions of this snippet over the years to narrow in on performance issues.

Read more...

Python type hints: How to pass Any for unused parameters in tests

When you create a function to match an interface, it often needs to accept parameters that it doesn’t use. Once you introduce type hints, testing such functions can become a little irksome as Mypy will require all arguments to have the correct types. Your tests can end up creating unused objects only to match the tested function’s signature. Here’s a technique to avoid that work.

Read more...

Python type hints: modernized error messages in Mypy 1.4.0

Mypy 1.4.0 was released last week (2023-06-20). I’m happy to see it includes three improvements that modernize error messages with newer type hint syntax:

Read more...

Django: Parametrized tests for all model admin classes

Here’s an application of “test smarter, not harder”, as per Luke Plant’s post. I came up with this recently whilst working on my client Silvr’s project, and I’m pretty proud of it. It should apply to any project using Django’s admin.

Read more...

How to download a documentation website with Wget

Sometimes you want to download a whole website so you have a local copy that you can browse offline. When programming, this is often useful for documentation that sites that do not provide downloadable versions, and are not available in offline tools like DevDocs.

Read more...

Django: How to profile and improve startup time

Your Django project’s startup time impacts how smooth it is to work with. Django has to restart your project every time you run a management command and when runserver reloads. This involves importing all your apps, and thus all the modules that they import.

Read more...

Python: unittest’s new context methods from Python 3.11 (with backports)

Python 3.11 only made one change to unittest, but it’s a good one: context manager methods. These methods can simplify setup and teardown logic in many cases, such as dynamic use of unittest.mock.

Read more...