Last active
November 20, 2023 11:51
-
-
Save tonyseek/0967775f8622e93418c8829814f2779c to your computer and use it in GitHub Desktop.
Parse __version__ from your Python package without importing it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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