Why can a Python package run code before I even import it?

November 20, 2026 4 answers
Asked by Mavquori-8x

I saw a scan reporting hundreds of PyPI packages with executable .pth files. How does that work, and will the move to .start files actually make it safer?

Answers

3n!Faldrix.82

Python's normal site initialization reads .pth files in site-packages. A line starting with import can execute at startup, so you don't have to import the package that installed it. That makes the feature useful for startup hooks, but also attractive to a malicious package.

The scan reported 684 packages with executable .pth files among the latest releases of 354,763 projects. That count includes 440 using old setuptools namespace boilerplate, not just packages with their own custom startup code. The scan also found some files in locations Python wouldn't read on Linux or macOS.

4w+bracketpouch_715:

Startup hooks aren't necessarily malicious, either. Some are conditional, while others can change behavior without an explicit import.

Reply to this answer
Marnz

The replacement doesn't remove the supply-chain risk. A .start file can still arrange for code to run at interpreter startup. The difference is that it names a module and function rather than putting arbitrary code on an import line, which should make startup hooks easier to find and audit.

Python 3.15 deprecates executable .pth lines, with the transition intended to culminate in them being ignored in 3.18. So check what a hook points to, not just which file extension it uses.

Reply to this answer
Zorvexa+5m

Only 13 of the 244 packages with their own startup code had a .start file in the scan, but I wouldn't read that as proof the rest will be broken forever. Maintainers often have to support several Python versions and may wait until a transition is closer before changing packaging behavior.

Reply to this answer
Mavqueno+2r

For a practical check, inspect the .pth files in the environment's site-packages directories for lines starting with import, then look at what those imports load. Treat unfamiliar startup hooks as a reason to investigate, not automatic proof of malware.

Virtual environments help contain package changes to a project. Pinning dependencies with hashes can also help you control which artifacts get installed, though neither makes a package you already trust inherently safe.

Mavquori-8x:

So the startup check is separate from checking what runs during installation?

_v57+quendrix.2:

Yes. Installing from source can involve running build code. Restricting pip to binary wheels avoids source builds, but a wheel can still contain a startup hook.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions