Search code examples
pythondependency-managementpyproject.toml

How to provide tomllib


Since python3.11 we are able to use builtin library tomllib before we had access to third party library tomli and a few others.

I did not have analyzed both packages deeply but came to the conclusion, that I am able to replace tomli with tomllib for my purposes.

My issue I have with the situation: How to handle the change while also supporting down to 3.9?

Is there a solution to provide different dependencies in pyproject.toml for different versions of python (with additons to codebase changes accordingly)?

This Question could be probably generalized, but I think the example gives a good picture of the general issue I face.


Solution

  • You can use PEP 496 – Environment Markers and PEP 508 – Dependency specification for Python Software Packages; they're usable in setup.py, setup.cfg, pyproject.toml, requirements.txt. In particular see PEP 631 – Dependency specification in pyproject.toml for pyproject.toml:

    [project]
    dependencies = [
        'tomli ; python_version < "3.11"'
    ]
    

    After installing or skipping tomli you test presence of tomllib/tomli in the code:

    try
        import tomllib
    except ImportError:
       try
           import tomli
       except ImportError:
          sys.exit('Error: This program requires either tomllib or tomli but neither is available')