Metadata-Version: 2.5
Name: pynamerx
Version: 0.1.0
Summary: A powerful, scope-aware Python source renamer/obfuscator that handles complex scenarios.
Project-URL: Homepage, https://github.com/pooraddyy/PyNamer
Project-URL: Repository, https://github.com/pooraddyy/PyNamer
Project-URL: Issues, https://github.com/pooraddyy/PyNamer/issues
Author: pooraddyy
License: MIT
License-File: LICENSE
Keywords: ast,minifier,obfuscation,remapper,renamer,symbol-table
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Software Development :: Build Tools
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Provides-Extra: test
Requires-Dist: pytest>=7.4; extra == 'test'
Description-Content-Type: text/markdown

# PyNamer

> A scope-aware Python **source renamer / obfuscator** that survives the hard
> cases: closures, `global`/`nonlocal`, keyword arguments, inheritance,
> comprehensions, walrus, `match`, `__slots__` and attributes.

PyNamer builds an **explicit scope tree** (much like CPython's own `symtable`),
performs a dedicated **attribute data-flow analysis**, and rewrites the AST in a
single, re-entrant pass.

```python
from pynamer import rename

obfuscated = rename(open("secret.py").read())
```

## Why it is more powerful

| Concern | Typical renamers | PyNamer |
| --- | --- | --- |
| Re-entrancy | module-level globals | full scope tree, no shared state |
| Attributes | rename everything / nothing | data-flow: only *locally defined* attributes, never externally observed ones |
| Keyword arguments | untouched / naive | remapped against the **resolved callee**, MRO-aware, incl. inherited `__init__` |
| Inheritance | blind | MRO walking for constructors & method kwargs |
| Comprehensions | leaky | correct Python 3 scoping (first iterable in the enclosing scope) |
| `getattr(obj, "x")` | broken | constant attribute strings remapped too |
| Names | readable `_0x1` | deterministic or hashed/compacted, collision-free |
| Minifier | monkey-patches the unparser | auditable token-aware whitespace pass |
| Cross-module | none | `RenameMap` gives package-wide, stable names |
| Safety | none | optional `compile()` validation, preservation lists |

## Install

```bash
pip install -e .          # from a checkout
# or
pip install -e ".[test]"
```

Requires Python 3.10+.

## CLI

```bash
pynamer module.py -o module.obf.py --prefix _0x --strategy base62
pynamer module.py --builtins --hide-init --strip-docstrings --stats
cat module.py | pynamer - --strategy hash --seed 7
python -m pynamer module.py --map-out map.json   # reuse later with --map-in
```

## Library API

```python
from pynamer import process, rename, rename_ast, RenameConfig, NameStrategy, RenameMap

# 1. simplest form -> string in, string out
out = rename(source)

# 2. full result object
result = process(source, strategy="hash", seed=1, builtins=True)
print(result.stats.as_dict())      # {"symbols": ..., "attributes": ...}
print(result.mapping.symbols)      # {"my_func": "_0x3", ...}
result.mapping.save("map.json")

# 3. AST in, AST out
new_tree = rename_ast(result.tree)

# 4. explicit config object
cfg = RenameConfig(strategy=NameStrategy.BASE62, prefix="_", minify=True)
out = rename(source, config=cfg)

# 5. package-wide stable renaming
shared = RenameMap.load("map.json")
for path in ("a.py", "b.py"):
    process(open(path).read(), map=shared)
shared.save("map.json")
```

## Configuration

Every option is a field on [`RenameConfig`](src/pynamer/config.py) and can be
passed as a keyword argument to `process`/`rename`:

| Option | Default | Meaning |
| --- | --- | --- |
| `strategy` | `"sequential"` | `sequential` / `hash` / `random` / `base62` / `words` |
| `seed` | `0` | seed for deterministic strategies |
| `prefix` | `"_0x"` | prefix for generated identifiers |
| `minify` | `True` | single-space indentation, no blank lines |
| `strip_docstrings` | `False` | drop module/class/function docstrings |
| `builtins` | `False` | alias builtins (`print`, `len`, …) at the top of the module |
| `hide_init` | `False` | obscure explicit constructors behind a forwarding method |
| `track_instances` | `False` | also rename local `Foo()`-instance variables |
| `rename_attributes` | `True` | rename locally defined attributes |
| `rename_kwargs` | `True` | remap keyword arguments of resolvable calls |
| `preserve` | `()` | names to never rename |
| `preserve_attributes` | `()` | attributes to never rename |
| `preserve_public` | `False` | keep public (non-underscore) module names |
| `validate` | `True` | re-`compile()` the result, raising on breakage |
| `map` | `None` | a `RenameMap` for cross-module stability |

## What is deliberately *not* renamed

* `__dunder__` names and the `super` builtin (zero-arg `super()` relies on the
  literal name for the `__class__` cell).
* `visit_*` methods by default (they form the `ast.NodeVisitor` protocol).
* `from __future__ import ...` feature names (they are compiler flags).
* Attributes that also appear on objects PyNamer cannot reason about, and any
  attribute reached through `super()` unless it is defined on a *local* base.
* Names listed in `preserve` / `preserve_attributes`.
* Parameter names that are passed as a keyword at a call site whose callee
  cannot be resolved statically (for example `receiver.method(x=1)` on an
  unknown object, or any `**mapping` call) - renaming them would silently break
  the call, so they keep their spelling.

## Known limitations

Renaming is a semantics-preserving source transformation *up to* reflection:

* A renamed class/function reports its new `__name__` / `__qualname__`,
  `__doc__` disappears when `strip_docstrings=True`, and an `Enum` member's
  `.name` reflects the new spelling. Avoid depending on those strings, or list
  the symbol in `preserve` / `preserve_attributes`.
* Dynamic name lookups via `globals()`, `eval`, `locals()` or non-constant
  `getattr(obj, some_variable)` cannot be tracked. Constant
  `getattr`/`setattr`/`hasattr`/`delattr` **are** handled.
* Attributes of classes whose bases live outside the processed source are left
  untouched (safe by default).

## Examples

Runnable examples live in [`examples/`](examples):

```bash
python examples/demo.py                                  # end-to-end demonstration
python examples/obfuscate.py examples/advanced_source.py # obfuscate & verify a file
python examples/obfuscate.py examples/advanced_source.py -o out.py --builtins
```

* `examples/sample.py` - a small `Money` program used by the demo.
* `examples/advanced_source.py` - a deliberately gnarly module (closures,
  `global`/`nonlocal`, kwargs across inheritance, `super()`, `__slots__`,
  `match`, walrus comprehensions, constant `getattr`).
* `examples/obfuscate.py` - obfuscates a file with the library API and asserts
  the obfuscated module still produces identical output.

## Testing

```bash
pip install -e ".[test]"
pytest                      # behaviour-preservation & unit tests
python examples/demo.py     # end-to-end demonstration
```

## License

MIT - see [LICENSE](LICENSE).
