Skip to content

Instantly share code, notes, and snippets.

@mierzejk
Last active April 5, 2024 08:20
Show Gist options
  • Save mierzejk/c4f0f177c75d14222c810dfb2eca8b0f to your computer and use it in GitHub Desktop.
Save mierzejk/c4f0f177c75d14222c810dfb2eca8b0f to your computer and use it in GitHub Desktop.
Get distribution package extras requirements with importlib_metadata library.
import pprint
import re
from collections import defaultdict
from functools import partial
from importlib_metadata import metadata
__semicolon_split = partial(str.split, sep=r';', maxsplit=1)
__package_split = re.compile(r'(?P<name>[^\s!~<>=(]+)\s*(?P<requirements>.*)')
__extra_re = re.compile(r'extra\s*==\s*\'(?P<name>\w+)\'')
def get_extras(dist_name: str) -> dict[str | None, list[tuple[str, str]]]:
requirements = defaultdict(list)
for g, key in ((__package_split.fullmatch(p).groups(),
(match := __extra_re.search((e or [r''])[0])) and match[r'name'])
for p, *e in map(__semicolon_split, metadata(dist_name).get_all(r'Requires-Dist')) ):
requirements[key].append(g)
return requirements
pprint.pp(get_extras('fastapi'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment