Running custom code on package install?

Hi @mte, AFAIK currently the packaging ecosystem in Python does not standardise any kind of mechanism for executing hooks upon installation[1].

Arbitrary code execution is always a complicated topic and can be very dangerous. I would not be surprised if the community never decides to treat this kind of use case as “tier 1”… The advice is to try avoid arbitrary code execution as much as possible.

There are a few techniques that can be used to get around this:

  1. Run arbitrary hooks upon the first program usage.
    You can use platformdirs to save a file into the user’s home directory once you have run the hook. This way you can avoid running it twice by checking if the file exists

  2. You can, in theory, distribute your package only as a sdist.
    This way the installer will be forced to transform the sdist into a wheel before installing it.
    You can take advantage of this to run a hook when building the wheel. However, to be frank this is a hack and I definitely don’t recommend that.


  1. I don’t know about conda packages. ↩︎

3 Likes