Announcing microvenv 2023.5

In my blog post explaining how virtual environments work, I announced my project called microvenv. At the time, my only goal was to create a package which could create virtual environments in a minimal, fast way. But since then, I have expanded the API of the package to provide some helpers I found myself and teammates at work needing. I also updated it to match a change coming to the venv module in Python 3.13.

Expanded API

Probably the newest part I'm most happy about is the activation() function which helps you "activate" your virtual environment. Normally when you run the shell script to activate your virtual environment, it sets the VIRTUAL_ENV environment variable and prepends the bin/ directory to PATH. The activation() function does this, but in a way designed to be additive to os.environ. What this means is the API is designed to be typically used as os.environ | microvenv.activation(). Because the union operator for dicts has the right-hand side take precedence, the updated value of PATH will mask the one from os.environ while adding VIRTUAL_ENV. And because | for dictionaries returns a new dict, you don't need to worry about deactivation as no in-place mutation of os.environ occurs.

There's also now a parse_config() function to parse the pyvenv.cfg file into a dict. The file is a custom format of key/value pairs that looks like an INI file with no section headers. Historically, people have parsed this file by adding a fake header via configparser and then parsing the file. But if you look at the code in the site module that actually processes the file, you will notice it doesn't use the configparser. As such, I wrote a function that uses the same algorithm to make it easier to get to.

I also tossed in IN_VIRTUAL_ENV and DEFAULT_ENV_DIR constants to detect when you're running from a virtual environment and the default name to use when creating a virtual environment, respectively.

.gitignore file in virtual environments

Starting in Python 3.13, virtual environments will contain a .gitignore file containing the text of * by default, and I have updated microvenv accordingly. This will cause Git to ignore the virtual environment directory. We did this because we regularly found beginners committing their virtual environments to source control without realizing that virtual environments are not portable between machines. We also view virtual environment contents as essentially an implementation detail, and so you shouldn't put your code in there as we reserve the right to do whatever we want in there which might clash with your files some day.

Miscellaneous

The project is now fully typed via .pyi files (due to wanting to keep the _create.py file as small as possible). Also, the project is now a package to once again keep _create.py small.