Beniget: Static Python Code Analysis

0.5.0 · active · verified Mon Apr 13

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.

Warnings

Install

Imports

Quickstart

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.

import beniget
import gast as ast # Use 'import ast' for Python >= 3.6 and beniget >= 0.5.0

# Example: Detect unused imports
code = """from math import cos, sin
print(cos(3))"""
module = ast.parse(code)

duc = beniget.DefUseChains()
duc.visit(module)

# Assuming the first body element is an ImportFrom statement
imported_names = module.body[0].names

for name in imported_names:
    # Find the corresponding definition-use chain for the imported name
    # Note: `name.name` gives the imported symbol, e.g., 'cos' or 'sin'
    ud_chain = duc.chains.get(name)
    if ud_chain and not ud_chain.users():
        print(f"Unused import: {ud_chain.name()}")

view raw JSON →