Skip to content

Instantly share code, notes, and snippets.

@tonyseek
Last active November 20, 2023 11:51
Show Gist options
  • Save tonyseek/0967775f8622e93418c8829814f2779c to your computer and use it in GitHub Desktop.
Save tonyseek/0967775f8622e93418c8829814f2779c to your computer and use it in GitHub Desktop.
Parse __version__ from your Python package without importing it
#!/usr/bin/env python3
import ast
from setuptools import setup
def parse_version(pkg_init_path, version_name='__version__'):
with open(pkg_init_path) as pkg_init_file:
pkg_init_ast = ast.parse(pkg_init_file.read())
return next(iter(
node.value.value
for node in pkg_init_ast.body
if isinstance(node, ast.Assign)
if len(node.targets) == 1
if isinstance(node.targets[0], ast.Name)
if node.targets[0].id == version_name
if isinstance(node.value, ast.Constant)
))
setup(
# ...
version=parse_version('YOUR_PACKAGE/__init__.py'),
# ...
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment