I use a pyproject.toml
file to list a package's dependencies:
[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"
[project]
name = "foobar"
version = "1.0"
requires-python = ">=3.8"
dependencies = [
"requests>=2.0",
"numpy",
"tomli;python_version<'3.11'",
]
Is is possible, from within the package, to get the list of its own dependencies as strings? In the above case, it should give
["requests", "numpy"]
if used with Python>=3.11, and
["requests", "numpy", "tomli"]
otherwise.
Something along the lines of the following should do the trick:
import importlib.metadata
import packaging.requirements
def _get_dependencies(name):
rd = metadata(name).get_all('Requires-Dist')
deps = []
for req in rd:
req = packaging.requirements.Requirement(req)
if req.marker is not None and not req.marker.evaluate():
continue
deps.append(req.name)
return deps
References: