Beniget is a static analyzer for Python code, providing compile-time analyses on Python Abstract Syntax Tree (AST). It offers over-approximation of global and local definitions and can compute def-use chains. It serves as a foundational building block for writing static analyzers or compilers for Python, relying on `gast` for cross-version AST abstraction and also supporting the standard library `ast` since version 0.5.0. It is actively maintained with periodic updates.
pip install benigetVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to use `beniget.DefUseChains` to identify unused imports in a Python code snippet. It parses the code into an AST (using `gast` for cross-version compatibility), computes def-use chains, and then checks if any imported names have no users.
Be aware of the limitations of static analysis when interpreting results from code that heavily relies on dynamic features.
For `beniget >= 0.5.0`, you can use either `gast` or the standard `ast` module. Ensure your AST parsing logic aligns with the version of `beniget` and `ast` library you are using. If targeting older Python versions or cross-version compatibility, `gast` is still recommended.
Always include `gast` in your project's dependencies and ensure it is installed alongside `beniget` (`pip install beniget gast`).
Install the 'gast' library using pip: `pip install gast` or `pip install beniget gast`
Upgrade 'gast' to a version compatible with your Python version and 'beniget' (e.g., `gast>=0.5.4` for Python 3.10+): `pip install --upgrade gast`
Ensure that the input to `beniget`'s analysis functions is a properly parsed AST object, typically obtained from `ast.parse()` or `gast.parse()`. For example: ```python import ast import beniget code = """def func(x):\n return x + 1""" ast_tree = ast.parse(code) duc = beniget.DefUseChains() duc.visit(ast_tree) ```