Originally published at https://jpscaletti.com/conditional-python-dependencies
Python 3.8 is almost here, so I've started adding it to my
tox.ini files. Soon, however, I found a problem.
One of my testing dependencies is PonyORM, a library that doesn't work with Python 3.8 yet. It's not even a hard dependency, just needed for a couple of tests, but it's making the whole library un-installable, and thus un-testable, on Python 3.8.
What should I do? Cancel any testing in the upcoming Python version until all of those soft-dependencies gets an update? For a moment, that seems to be the only option, but there is a much better one: environment markers.
Environment markers are conditions that you can add to any of your dependencies, so only if the evaluate to True the dependency is installed. In my case, I change the Pony requirement to:
That makes Pony a requirement, but only for versions of Python less than 3.8. So the library now can be installed, but the tests fail because they can't import Pony. I should disable them with an "if" statement:
# test_with_pony.py try: import pony except ImportError: pony = None if pony: # my tests here ...
Problem solved! The library install and all the tests (except those two, obviously), get tested under python 3.8. 🎉
The "environment markers" are powerful and can test for not only the python version, but also the operating system, platform, and python interpreter. And they work everywhere:
setup.cfg, or even
This might be old news for you because the environment markers have been out for years. However, I didn't knew or remember them. By writing this, I hope to not forget about them (again? 😕).