cd /news/developer-tools/show-hn-i-built-a-python-obfuscator-… Β· home β€Ί topics β€Ί developer-tools β€Ί article
[ARTICLE Β· art-82683] src=github.com β†— pub= topic=developer-tools verified=true sentiment=↑ positive

Show HN: I built a Python obfuscator that keeps production traces debuggable

Zhurong2020 released pyobfus v0.5.4, an open-source AST-based Python obfuscator supporting Python 3.9 through 3.14, with framework-aware presets, reverse stack-trace mapping for AI-assisted debugging, and a machine-readable JSON CLI for AI coding agents. The new version adds device-locked Runtime String Vault keys and includes a companion MCP server, pyobfus-mcp, registered in the official MCP Registry, enabling Claude Code, Cursor, and other agents to call pyobfus tools directly.

read16 min views1 publishedAug 1, 2026
Show HN: I built a Python obfuscator that keeps production traces debuggable
Image: source

pyobfus (pronounced as "Python obfuscator") is a modern, AST-based python-obfuscator / code-obfuscator with framework-aware presets, reverse stack-trace mapping for AI-assisted debugging, and a machine-readable JSON CLI designed for Claude Code, Cursor, and MCP agents. A transparent, open-source alternative to PyArmor.

A Python code obfuscator built with AST-based transformations. Supports Python 3.9 through 3.14. Provides reliable name mangling, string encoding, control-flow flattening, AES-256 string encryption, and β€” unique to pyobfus β€” a reverse-mapping workflow that lets you (or your AI coding assistant) debug obfuscated stack traces without giving up the protection.

πŸ†• What's new in v0.5.4β€”, not just Selective Opacity's L3 layer. Vault keys previously shipped as baked literals, so vault secrets decrypted on any machine; now each vault's key is re-derived at runtime from the bound device and a wrong machine is refused. The other patent-targeted--bind-device

now device-locks Runtime String Vault keys tooPro mechanismsremain one-line flags: Selective Opacity (per-symbol AES-256 layers), forensic watermarking,@seal_code

integrity, traceback scrubbing,--period

(run-counter limit) and--opacity-config

(pattern-driven L3 encryption by original qualname). Pro flags are used aspyobfus SRC -o OUT --level pro --<flag>

. Full details in the[CHANGELOG]; see[Pro Edition]below.

πŸ”Œ Companion MCP server: pyobfus-mcp #

pyobfus-mcp

This repository ships two installable packages:

Package What it is Install
pyobfus

pip install pyobfus

pyobfus-mcp

Model Context Protocol (MCP) server that exposes pyobfus's tools to AI coding agents.uvx pyobfus-mcp

(zero-install) or pip install pyobfus-mcp

The MCP server lives in pyobfus_mcp/ and is built on the official

Model Context Protocol Python SDK(FastMCP). It registers eight MCP tools so

Claude Desktop, Claude Code, Cursor, Windsurf, and Zed can call pyobfus directly from agent conversations β€” no shelling out:

MCP tool Implementation Purpose
protect_project
pyobfus_mcp/tools.py

One-call, self-verifying pipeline: scan β†’ preset β†’ obfuscate β†’ byte-compile + import-smoke-test the output β†’ returnverified: true/false

. The agent reports a green check instead of hoping the transform didn't break anythingcheck_obfuscation_risks

pyobfus_mcp/tools.py

generate_pyobfus_config

pyobfus_mcp/tools.py

pyobfus.yaml

unmap_stack_trace

pyobfus_mcp/tools.py

list_presets

pyobfus_mcp/tools.py

explain_preset

pyobfus_mcp/tools.py

recommend_tier

pyobfus_mcp/tools.py

start_pro_trial

pyobfus_mcp/tools.py

The server is registered in the official MCP Registry under

io.github.zhurong2020/pyobfus-mcp

. The transport is stdio. See for per-client configuration snippets.

pyobfus_mcp/README.md

This repo is also a Claude Code plugin marketplace. The pyobfus-protect

skill teaches an agent the full "protect Python before shipping β€” obfuscate and verify it still runs" workflow (MCP-first, CLI fallback):

/plugin marketplace add zhurong2020/pyobfus
/plugin install pyobfus@pyobfus

See skills/ for the skill and install details. (This is distinct from

, which are copy-in rule files for

templates/ai-integration/

yourproject.)

β€” pre-flight risk scan: detectspyobfus --check src/

eval

/exec

, dynamic attribute access, and framework reflection points before you obfuscate. JSON output with anai_hint

telling your AI assistant what to run next.β€” zero-config onboarding: scans the project, detects FastAPI/Django/Pydantic/Click/SQLAlchemy, and writes a ready-to-usepyobfus --init src/

pyobfus.yaml

.β€” reverse obfuscated identifiers in a production stack trace so you can debug (or hand the trace to an AI assistant) without reversing the obfuscation itself.pyobfus --unmap --trace error.log --mapping mapping.json

β€” stamp each obfuscated file with apyobfus … --save-mapping mapping.json --trace-marker

# pyobfus:obfuscated

header (id + mapping filename + the exact--unmap

command) so an AI agent that lands in an obfuscated file from a traceback immediately knows it's pyobfus output and how to reverse the names.Framework-aware presetsβ€”--preset fastapi | django | flask | pydantic | click | sqlalchemy

with built-in exclusions for dispatch methods, decorators, ORM fields, migrations, and dependency-injection parameters.Globalβ€” every CLI mode (--json

obfuscate

,--check

,--unmap

,--init

) emits the same structured schema with anai_hint

field, ready for Claude Code, Cursor, Windsurf, and MCP servers to consume.

The following features are fully implemented and available in the current version:

πŸ†• Cross-File Obfuscation(v0.2.0): Consistent name obfuscation across multiple files- Automatic import statement rewriting __all__

list updates with obfuscated names- Global symbol table with collision detection

  • Two-phase obfuscation pipeline (Scan β†’ Transform)
  • Preview mode with --dry-run

flag

Name Mangling: Rename variables, functions, classes, and class attributes to obfuscated names (I0, I1, I2...) - Comment Removal: Strip comments and docstrings - String Encoding: Base64 encoding for string literals with automatic decoder injection - Parameter Preservation: Preserve function parameter names for keyword argument compatibility (--preserve-param-names

) - Multi-file Support: Obfuscate entire projects with preserved import relationships - File Filtering: Exclude files using glob patterns (test files, config files, etc.) - Configuration Files: YAML-based configuration for repeatable builds - Selective Obfuscation: Preserve specific names (builtins, magic methods, custom exclusions)

The following advanced features are available with a Pro license:

String Encryption(v0.1.6+)- AES-256 encryption for strings

  • Runtime decryption with injected decoder

  • Automatic key generation

Anti-Debugging(v0.1.6+)- Debugger detection checks injected into functions

  • Multiple detection methods (sys.gettrace, sys.settrace)

  • Configurable behavior

Control Flow Flattening(v0.3.0+)- State machine transformation for if/else/elif

  • For/while loop flattening

  • Nested structure support

  • CLI: --control-flow

Dead Code Injection(v0.3.0+)- Insertion of unreachable code paths

  • Four strategies: after-return, false branches, opaque predicates, decoy functions

  • CLI: --dead-code

License Embedding(v0.3.0+)- Embed expiration dates: --expire 2025-12-31

  • Machine binding: --bind-machine

  • Run count limits: --max-runs 100

  • Offline verification - no external dependencies

  • Embed expiration dates:

Configuration Presets(v0.3.0+)--preset trial

  • 30-day time-limited version--preset commercial

  • Maximum protection with machine binding--preset library

  • For pip-distributable libraries--preset maximum

  • Highest security with all protections--list-presets

  • View all presets

Six mechanisms, available both as the pyobfus_pro

API and β€” as of v0.5.1 β€” as opt-in pyobfus

build flags (single-file / --no-cross-file

mode): --selective-opacity

, --seal-code

, --vault

, --scrub-traceback

, --fingerprint <buyer-id>

, --expire-hard <date>

. v0.5.3 adds --period <N>

(run-counter limit), --opacity-config <opacity.toml>

(pattern-driven L3 encryption by original qualname), and --bind-device

/ --bind-device-id <id>

(device-locked L3 encryption).

Selective Opacityβ€” per-symbol protection layers (transparent / ai-readable / obfuscated / AES-256-GCM encrypted with lazy__code__

materialization).Forensic watermarkingβ€” per-buyer deterministic key derivation for piracy traceback.** License binding combo**β€” device / expiry / run-count binding woven into the AES-GCM decryption path (no separate patchable license check).β€” build-time bytecode integrity hash; runtime in-memory-patch detection.@seal_code

β€” production traceback encryption (RSA-2048 + AES-256-GCM); reverse error IDs with the new--scrub-traceback

pyobfus-unscrub

CLI.Runtime String Vaultβ€” encrypted KV namespace for runtime secrets with lazy per-entry decryption.

Requires Python β‰₯ 3.9 as of v0.5.0 (3.8 dropped, EOL 2024-10).

See ROADMAP.md for the full feature timeline.

Try all Pro features for 5 days - no registration or credit card required!

pyobfus-trial start

pyobfus-trial status

pyobfus input.py -o output.py --level pro

What's included in the trial:

  • Control flow flattening ( --control-flow

) - AES-256 string encryption ( --string-encryption

) - Anti-debugging protection ( --anti-debug

) - Dead code injection ( --dead-code

) - License embedding ( --expire

,--bind-machine

,--max-runs

) - Configuration presets ( --preset trial/commercial/library/maximum

) - Unlimited files and lines of code

After your trial, purchase a license to continue using Pro features.

The trial runs on the honor system.It stores its state in an unsigned file in your home directory, andpyobfus/trial.py

is readable Apache-2.0 source β€” so it is a convenience control, not a security boundary, and we document it as such rather than claiming protection it cannot deliver. See[SECURITY.md]. Note that theCommunity Edition has no file or line limits and needs no trial at allβ€” the trial gates only the Pro mechanisms.

Pro Edition Features:

  • πŸ”€ Control Flow Flattening (v0.3.0+)
  • 🧩 Dead Code Injection (v0.3.0+)
  • πŸ” AES-256 String Encryption
  • πŸ›‘οΈ Anti-Debugging Checks
  • πŸ“… License Embedding (v0.3.0+) - Expiration, machine binding, run limits
  • ⚑ Configuration Presets (v0.3.0+) - One-command setup
  • πŸ”„ Lifetime Updates
  • πŸ’» Up to 3 devices per license
  • πŸ“§ Priority Email Support

Price: $45.00 USD (one-time payment)

Visit our purchase page: ** pyobfus.github.io/purchase** for detailed information and secure checkout.

Quick purchase: ** πŸš€ Buy Now** - Direct checkout link (Instant delivery β€’ 30-day money-back guarantee)

3-Step Purchase Process:

Complete Secure Checkout(Stripe)- Click the buy link above or visit the purchase page

  • Enter your email (for license delivery)

  • Complete payment securely via Stripe

Receive License Key- License key delivered to your email within minutes

  • Format: PYOB-XXXX-XXXX-XXXX-XXXX

Check Spam/Junk folder if not in inbox

Activate License

pip install --upgrade pyobfus
pyobfus-license register PYOB-XXXX-XXXX-XXXX-XXXX
pyobfus-license status

Start Using Pro Features

pyobfus src/ -o dist/ --preset commercial   # Maximum protection
pyobfus src/ -o dist/ --preset trial        # 30-day trial version
pyobfus src/ -o dist/ --preset library      # For pip distribution

pyobfus input.py -o output.py --string-encryption
pyobfus input.py -o output.py --anti-debug
pyobfus input.py -o output.py --control-flow
pyobfus input.py -o output.py --dead-code

pyobfus src/ -o dist/ --expire 2025-12-31 --bind-machine --max-runs 100

pyobfus input.py -o output.py --string-encryption --anti-debug --control-flow --dead-code

Support: If you encounter any issues, contact zhurong0525@gmail.com with your license key.

By purchasing pyobfus Professional Edition, you agree to our:

From PyPI (recommended):

pip install pyobfus

From source (for development):

git clone https://github.com/zhurong2020/pyobfus.git
cd pyobfus
pip install -e .
pyobfus input.py -o output.py

pyobfus src/ -o dist/

pyobfus src/ -o dist/ --dry-run

pyobfus src/ -o dist/ --no-cross-file

pyobfus src/ -o dist/ --config pyobfus.yaml

pyobfus src/ -o dist/ --preserve-param-names

pyobfus src/ -o dist/ --verbose

Before obfuscation:

def calculate_risk(age, score):
    """Calculate risk factor."""
    risk_factor = 0.1
    if score > 100:
        risk_factor = 0.5
    return age * risk_factor

patient_age = 55
patient_score = 150
risk = calculate_risk(patient_age, patient_score)
print(f"Risk score: {risk}")

After obfuscation:

def I0(I1, I2):
    I3 = 0.1
    if I2 > 100:
        I3 = 0.5
    return I1 * I3
I4 = 55
I5 = 150
I6 = I0(I4, I5)
print(f'Risk score: {I6}')

Note: Variable names (I0, I1, etc.) may vary slightly depending on code structure, but functionality is preserved.

Generate a configuration template for your project type:

pyobfus --init-config django

pyobfus --init-config flask

pyobfus --init-config library

pyobfus --init-config general

This creates a pyobfus.yaml

file with sensible defaults for your project type.

Check your configuration file for errors before use:

pyobfus --validate-config pyobfus.yaml

The validator checks for:

  • YAML syntax errors
  • Invalid configuration options
  • Common typos (e.g., exclude_pattern

->exclude_patterns

) - Pro features used with community level

When you run pyobfus

without -c

, it automatically searches for:

pyobfus.yaml

pyobfus.yml

.pyobfus.yaml

.pyobfus.yml

Create pyobfus.yaml

:

obfuscation:
  level: community
  exclude_patterns:
    - "test_*.py"
    - "**/tests/**"
    - "__init__.py"
  exclude_names:
    - "logger"
    - "config"
    - "main"
  remove_docstrings: true
  remove_comments: true

The exclude_names

option preserves specified names from being renamed during obfuscation:

obfuscation:
  exclude_names:
    - MyPublicClass      # Name preserved, but strings inside are still encoded
    - exported_function  # Name preserved for external callers

Important: exclude_names

only affects name obfuscation, not string encoding:

SECRET_KEY = "admin-password-123"

SECRET_KEY = _decode_str('YWRtaW4tcGFzc3dvcmQtMTIz')

Use cases:

  • Preserve names for public APIs that external code imports
  • Keep class/function names for debugging while still protecting string content
  • Maintain compatibility with external frameworks expecting specific names

Exclude patterns support glob syntax:

test_*.py

  • Exclude files starting with "test_"**/tests/**

  • Exclude all files in "tests" directories**/__init__.py

  • Exclude all__init__.py

filessetup.py

  • Exclude specific files

See pyobfus.yaml.example

for more configuration examples.

pyobfus uses Python's ast

module for syntax-aware transformations:

Parser: Parse Python source to AST** Analyzer**: Build symbol table with scope analysis** Transformers**: Apply obfuscation techniques (name mangling, string encoding, etc.)** Generator**: Generate obfuscated Python code

This approach ensures:

  • Syntactically correct output
  • Proper handling of Python scoping rules
  • Support for modern Python features (f-strings, walrus operator, etc.)
git clone https://github.com/zhurong2020/pyobfus.git
cd pyobfus
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate
pip install -e ".[dev]"
pytest tests/ -v

pytest tests/ -v --cov=pyobfus --cov-report=html

pytest integration_tests/ -v

Integration Testing Framework (v0.1.6+): Test pyobfus on real-world code without up to PyPI. See INTEGRATION_TESTING.md for details.

black pyobfus/

mypy pyobfus/

ruff check pyobfus/

Obfuscate sensitive business logic before distributing Python applications.

Demonstrate code protection concepts and obfuscation techniques.

Add an additional layer of protection for commercial Python software.

Keyword Arguments(βœ… Resolved in v0.1.6): By default, parameter names are obfuscated, which breaks keyword arguments.** Solution**: Use the--preserve-param-names

flag to preserve parameter names while still obfuscating function bodies.Example:

def process(data_path, output_dir):
    temp_file = data_path + ".tmp"
    return temp_file

result = process(data_path='./data', output_dir='./output')  # βœ… Works

def I0(I1, I2):
    I3 = I1 + ".tmp"
    return I3

result = process(data_path='./data', output_dir='./output')  # ❌ TypeError!

def I0(data_path, output_dir):
    I3 = data_path + ".tmp"
    return I3

result = I0(data_path='./data', output_dir='./output')  # βœ… Works!

When to use:--preserve-param-names

  • Public API functions/libraries where keyword arguments are used by clients
  • Functions with many parameters where keyword arguments improve readability
  • Code that relies heavily on keyword-only arguments ( def func(*, kwonly)

)

Trade-off: Parameter names reveal some information about the function's interface, but function bodies and local variables are still fully obfuscated. - Cross-file imports: βœ… Resolved in v0.2.0 with full cross-file obfuscation support - Dynamic code:eval()

,exec()

with obfuscated code may require adjustments - Debugging: Obfuscated code is harder to debug (by design) - Performance: Some obfuscation techniques may impact runtime performance

Test obfuscated code thoroughly before deployment- Keep original source in version control

  • Use configuration files for reproducible builds
  • For public APIs, use --preserve-param-names

to maintain keyword argument compatibility - Consider combining with other protection methods (compilation, etc.)

Python Support: 3.9, 3.10, 3.11, 3.12, 3.13, 3.14** Naming Scheme**: Index-based (I0, I1, I2...) - simple and effective** Architecture**: Modular transformer pipeline with two-phase cross-file obfuscation** Testing**: 1,000+ tests, 90% coverage, multi-OS CI/CD (Python 3.9-3.14 Γ— Ubuntu / macOS / Windows)

Use pyobfus if you:

  • Need to protect proprietary algorithms before distributing Python applications
  • Want a tool that "just works" without DLL conflicts or native dependencies
  • Prefer transparent pricing without hidden trial limitations
  • Support open-source software with optional paid features
pip install pyobfus

pyobfus script.py -o script_obf.py

pyobfus src/ -o dist/

pyobfus src/ -o dist/ --dry-run

pyobfus is designed to preserve program behavior for supported Python syntax and framework patterns, and its compatibility matrix is covered by automated tests. Obfuscation is still a source transformation: run your own test suite and verify the built artifact, especially when the project relies on dynamic imports, reflection, or generated code.

Minimal impact:

Name mangling: Zero runtime cost (just renamed identifiers)** String encoding**(Base64): ~0.1ms per string at startup** String encryption**(AES-256, Pro): ~0.5ms per string at startup

Yes! Use our built-in templates:

pyobfus --init-config django

pyobfus --init-config flask

pyobfus src/ -o dist/ -c pyobfus.yaml

pyobfus supports Python 3.9 through 3.14. Build and test the obfuscated artifact with the Python version used in production; cross-interpreter portability can depend on syntax, dependencies, and enabled transformations.

Feature pyobfus PyArmor
Price
$45 (Pro) $89 (Pro)
Free tier
Clear limits (5 files/1000 LOC) Vague "trial" limitations
Open source
Yes (Core: Apache 2.0, Pro: Proprietary) No
Native dependencies
None (pure Python output) Requires runtime library
Python 3.12 support
Yes Yes

Choose pyobfus if: You want transparent pricing, open-source trust, and simpler deployment without native dependencies.

See our detailed comparison for more information.

Yes β€” and for many projects this is the most cost-effective approach. Use pyobfus as your always-on default layer (every module gets AST mangling + mapping for AI-debug compatibility), then stack PyArmor Pro's bytecode encryption or Nuitka's native compilation on the small set of modules that genuinely need stronger protection. See Layered Deployment Strategy in COMPARISON.md for the full reasoning.

Use to preview changes before writing files--dry-run

Use if you rely on keyword arguments--preserve-param-names

Add exclusions inpyobfus.yaml

for names that must stay unchangedReport issues onGitHub- we fix bugs quickly!

Name mangling removes the original identifiers from the emitted source and raises the cost of analysis, but it is not cryptographically irreversible: a determined analyst may infer names and behavior from context. Keep the optional mapping file private when you need reliable reverse mapping. For stronger protection, use Pro features:

AES-256 encryption for stringsAnti-debugging checks to prevent analysis

Important: String encryption (AES-256) is designed as a deterrent against casual reverse engineering, not as cryptographic security.

Because obfuscated code must decrypt strings at runtime, the encryption key is necessarily embedded in the output. A determined attacker with access to the obfuscated code can:

  • Locate the embedded key
  • Extract and decrypt all strings

This is a fundamental limitation of ALL client-side obfuscators (including PyArmor, Nuitka, etc.) - true cryptographic security would require server-side decryption, which is impractical for most use cases.

What string encryption DOES provide:

  • βœ… Prevents casual strings

orgrep

searches from revealing sensitive text - βœ… Increases effort required for reverse engineering

  • βœ… Deters non-technical users from extracting information
  • βœ… Adds a layer of protection combined with other techniques

What string encryption does NOT provide:

  • ❌ Protection against determined reverse engineers
  • ❌ Cryptographic security for secrets (use environment variables or secret management instead)
  • ❌ DRM-level protection

Recommendation: For sensitive credentials (API keys, passwords), use environment variables or external secret management systems rather than embedding them in code.

Tool Approach Output
pyobfus
AST transformation .py files (pure Python)
Cython
Compile to C .so /.pyd (platform-specific)
Nuitka
Compile to executable Binary (platform-specific)

Choose pyobfus if: You need cross-platform .py

files without compilation overhead.

Dual License Model(see):LICENSE-NOTICE.md

pyobfus(Core):Apache 2.0- Free and open source** pyobfus_pro**(Pro):Proprietary- Requires paid license

If you find pyobfus helpful, consider supporting its development:

Your support helps maintain and improve pyobfus. Thank you!

If you use pyobfus in academic work or want to reference it, please cite the archived release. The concept DOI below always resolves to the latest version:

APA

Zhu, R. (2026).

pyobfus: An AST-based Python obfuscator with reverse stack-trace mapping for AI-assisted development. Zenodo.[https://doi.org/10.5281/zenodo.20846053]

BibTeX

@software{zhu_pyobfus,
  author    = {Zhu, Rong},
  title     = {pyobfus: An AST-based Python obfuscator with reverse stack-trace mapping for AI-assisted development},
  year      = {2026},
  publisher = {Zenodo},
  doi       = {10.5281/zenodo.20846053},
  url       = {https://doi.org/10.5281/zenodo.20846053}
}

Machine-readable metadata is in CITATION.cff (GitHub's "Cite this repository" widget reads it).

  • Inspired by Opy's AST-based approach - Clean room implementation - no code copying
── more in #developer-tools 4 stories Β· sorted by recency
── more on @pyobfus 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain β€” perfect for shipping the agent you just read about.

$git push zahid main
β†’ Live at https://your-agent.zahid.host βœ“
Get free account β†’ Pricing
from €0/mo Β· no card required
LIVE [news/show-hn-i-built-a-py…] indexed:0 read:16min 2026-08-01 Β· β€”