// HACKER NEWS — CYBERSECURITY
Working to Make Python Lazy
Python 3.15a7, which is now just a uv python install 3.15 away on all major
platforms, has lazy imports! This exciting feature, proposed in PEP 810,
promises to make CLI applications faster (especially when using flags like
--help), and could make a lot of large code with lots of imports that don’t
always get used faster too. Unlike the earlier, failed attempt, this requires
libraries to put in some work. I’ve developed a helper tool to make it easy; I’d
like to cover what lazy imports are and how to use my tool. Since this is the
first library that I used AI heavily in developing, the second half of the post
will cover how my experience with AI for a task like this went.
TL;DR: run uvx flake8-lazy --apply=list to make your code magically faster on
Python 3.15!
Imagine you have a file like this, with a standard Python argparse CLI:
What happens if you run this with --help? The numpy library will be
imported, even though it is never used. If you are using modern uv tooling,
this can be even worse, since uv doesn’t pre-compile bytecode unless you ask
it to; that makes the install faster, but imports are slower the first time.
The above is just one example; this can also happen when you have this common
pattern:
The idea behind this is that a user can just use lib.a.stuff with just
import lib, rather than import lib.a, but you pay the cost of import even if
they never use all the imports. Some libraries, like rich, are careful to
avoid this and ask users to import explicitly, but many older libraries did
this.
And there are also libraries that can do multiple things (like CLI libraries
with subcommands), but you don’t need the dependencies for every subcommand.
Take the first example. In Python 3.15, you can now write:
Now, both imports are “lazy”, meaning nothing happens at all when you import
them. They might not even be installed. The first time you try to use the
object, though, it becomes a real, imported object. So if you do --help,
numpy is never accessed and never imported.
This works on older Pythons (it’s just not lazy), and you can also dynamically
generate or manipulate that list if you want. Linters like Ruff have already
updated to allow this to be placed above your imports without triggering a lint
violation.