The package.py execution model and the errors it produces — why a top-level `from x import SomeClass` makes the installed package.py unparseable, why module-scope values are frozen on the build machine, why `env`/`this`/`root` look undefined to linters, and why a failed rez-build can leave a broken install behind. Use when a package resolves or builds with a confusing error, when reviewing a package.py for module-scope mistakes, or before releasing one. Covers Rez 3.4.0.
---
name: rez-package-pitfalls
description: "The package.py execution model and the errors it produces — why a top-level `from x import SomeClass` makes the installed package.py unparseable, why module-scope values are frozen on the build machine, why `env`/`this`/`root` look undefined to linters, and why a failed rez-build can leave a broken install behind. Use when a package resolves or builds with a confusing error, when reviewing a package.py for module-scope mistakes, or before releasing one. Covers Rez 3.4.0."
---
# Rez `package.py` pitfalls
> **One-sentence summary**: rez `exec`s `package.py` once at build time and writes every surviving
> module-level name back out as Python source, so anything at module scope that is not a plain
> value, a function or a module lands in the installed `package.py` as text that no longer parses.
Skill scope: **what rez does to `package.py` and when**. For the attribute reference and the
`@early`/`@late` mechanics see `rez-package-definition`; for the `commands()` body and the rex API
see `rez-package-commands`; for the version/variant/range decisions and the rest of the
anti-pattern list see `rez-package-authoring`.
Every pitfall below was reproduced against Rez 3.4.0, and the error text is copied from a real
run with only the host, user and timestamp replaced by placeholders.
## The three phases
| Phase | When it runs | What it does to `package.py` |
|---|---|---|
| **Load** | every time rez reads a package, including during `rez-build` | `exec`s the file; every module-level name is collected as a candidate attribute |
| **Serialize** | on `rez-build` / `rez-release` | writes the surviving attributes back out as a new `package.py` into the install |
| **Interpret** | on `rez-env` and every other resolve | runs `commands()` through rex and emits shell code; **does not** run the module body |
Two consequences drive every pitfall here: the module body is **Python** evaluated **on the build
machine**, and `commands()` is **not** Python at resolve time.
## Pitfall 1 — a top-level `from x import SomeClass` breaks the installed package
### Symptom
`rez-build --install` fails while *resolving the build environment*, before your build command ever
runs. The named file is a temporary copy, not your source.
### Trigger
Any module-level name bound to something that is not a plain value, a function, a module or a
`__`-leading name. The most common shape is importing a **class** at the top of the file:
```python
from pathlib import Path # Path is a class, so it survives serialization
documents_path = Path.home().as_posix() + "/Documents/.p4config"
name = "foo"
version = "1.0.0"
```
### Actual error
```text
Resolving build environment:
resolved by builder@BUILD-HOST, on Fri Oct 02 01:05:17 2026, using Rez v3.4.0
requested packages:
~platform==windows (implicit)
~arch==AMD64 (implicit)
~os==windows-10.0.26100.SP0 (implicit)
resolved packages:
01:05:17 ERROR ResourceError: Problem loading C:\Users\<user>\AppData\Local\Temp\rez_write__epzwl2x\package.py: invalid syntax (package.py, line 12)
Invoking custom build system...
```
The `rez_write_<random>` directory is rez's own temp copy of the definition
(`rez/serialise.py`, `prefix="rez_write_"`), so the path in the message never points at the file you
edited. The offending line is what rez wrote, not what you wrote — here line 12 of the generated
file is:
```python
Path = <class 'pathlib.Path'>
```
`package.py` attributes are dumped with `pformat()`, and the `repr` of a class object is not valid
Python source.
### Correct form
Import inside `commands()`, and keep the value out of the module scope entirely:
```python
name = "foo"
version = "1.0.0"
def commands():
# Import inside commands() so the module is not captured as a package
# attribute: rez serializes module-level names into the installed
# package.py, and a class object renders as invalid syntax.
from pathlib import Path
documents_path = Path.home().as_posix() + "/Documents/.p4config"
env.P4CONFIG.set(documents_path)
```
The installed `package.py` then carries `name`, `version`, `commands`, `timestamp` and
`format_version` — and nothing else. The last two are rez's, not yours: `timestamp` defaults to the
install time and `format_version` is always written by the filesystem package repository
(`rezplugins/package_repository/filesystem.py`), so expect both after every `rez-build --install`.
## Pitfall 2 — module-scope values are frozen on the build machine
### Symptom
A package works on the machine that released it and is wrong everywhere else: a per-user path, a
hostname, a `sys.prefix` or a `os.getcwd()` result points at the *builder's* machine.
### Trigger
Computing anything environment-dependent at module scope:
```python
import sys
from pathlib import Path
sys_path = sys.prefix # frozen at build time
documents_path = Path.home().as_posix() + "/Documents/.p4config"
```
### Why
The module body runs once, during `rez-build`, and its **results** are written into the install.
This is what lands in the installed `package.py`:
```python
sys_path = 'C:\\Users\\<user>\\AppData\\Local\\Programs\\Python\\Python312'
documents_path = 'C:/Users/<user>/Documents/.p4config'
```
Note that `sys_path` survived even though `sys` itself did not — the module was stripped, the string
it produced was not.
### Correct form
Move anything that depends on *who* or *where* the resolve runs into `commands()`, which is
interpreted on the consumer's machine at resolve time:
```python
def commands():
from pathlib import Path
env.P4CONFIG.set(Path.home().as_posix() + "/Documents/.p4config")
```
Use `@early()` only for values that are genuinely a property of the build — see
`rez-package-definition`.
## Pitfall 3 — `env`, `this` and `root` are undefined names to your linter
### Symptom
Your editor or CI linter flags `package.py` even though it works perfectly in rez.
### Trigger
Any use of a name that rez injects. Rez binds `this`, `version`, `root` and `base` only while it
interprets `commands()` (`resolved_context.py`), and `env` is the rex environment object. None of
them exists when the file is read as ordinary Python.
### Actual error
```text
F821 Undefined name `env`
--> package.py:6:5
|
5 | def commands():
6 | env.PYTHONPATH.prepend("{this.root}/site-packages")
| ^^^
```
### Correct form
Silence it at the point of use, which documents the intent for the next reader:
```python
env.PYTHONPATH.prepend("{this.root}/site-packages") # noqa: F821
env.RESOURCE_PATH.prepend("{this.root}/resource") # noqa: F821
```
Do not "fix" it by defining `env` or `root` yourself at module scope — that shadows rez's binding and
creates a real package attribute that then gets serialized (pitfall 1 and 2).
## Pitfall 4 — a failed build can leave a broken install on the package path
### Symptom
You fix `package.py`, rebuild, and the *same* error comes back — now naming the installed copy
instead of a temp file.
### Trigger
A failed `rez-build --install` leaves a package behind whenever the run got as far as writing the
install. Whether it did depends on where the build stopped: the failure in pitfall 1 happens while
resolving the build environment, before the build system is invoked, so that run installs nothing —
but a failure during or after the install step does leave the payload in place. When an install is
left behind, every later resolve and every later build of that package fails while reading it,
whatever your source now says.
### Correct form
Check whether the failed run left an install behind before deleting anything — the answer is not
always yes:
```bash
rez-search foo # is foo visible, and at which version?
```
If it is, remove that version and rebuild:
```bash
rm -rf <packages_path>/foo/1.0.0
rez-build --install
```
Then verify in a fresh resolve, not in the build shell:
```bash
rez-env foo
rez-context --so
```
## What survives at module scope
Reproduced on 3.4.0 by loading each snippet and dumping the installed form:
| Module-level statement | Survives? | Written as |
|---|---|---|
| `import sys` | no — module stripped | — |
| `sys_path = sys.prefix` | **yes** | `'C:\\Users\\<user>\\...\\Python312'` (build machine) |
| `from os.path import join` | no — function stripped | — |
| `def _helper(): ...` | no — plain function stripped | — |
| `from pathlib import Path` | **yes** | `Path = <class 'pathlib.Path'>` — unparseable |
| `class Helper: ...` | **yes** | `Helper = <class 'Helper'>` — unparseable |
| `my_re = re.compile(r'foo-\d+')` | **yes** | `my_re = re.compile('foo-\\d+')` — parses, then `NameError: name 're' is not defined` |
| `my_const = 'hello'` | **yes** | `'hello'` — a normal attribute, this is the intended use |
The rule rez applies is narrow: it strips **modules**, **functions** (except `commands`,
`pre_commands`, `post_commands`, `pre_build_commands`, `pre_test_commands`, `preprocess`, `@early`
and `@late`) and `__`-leading names. Everything else stays.
Surviving values fail in two different ways, and which one you get tells you where to look. A
`repr` that is not valid Python (`Path = <class 'pathlib.Path'>`) fails while **parsing**, with
`invalid syntax`. A `repr` that *is* valid Python but names a stripped module
(`my_re = re.compile(...)`) parses cleanly and fails while **executing**, with `NameError`. Both
reach you as `ResourceError: Problem loading <path>: <reason>`, so read the reason, not just the
exception type.
## Review checklist
- [ ] No class, instance or other non-plain object is bound at module scope — imports live inside
`commands()` or inside `@late()`.
- [ ] Nothing environment-dependent (`Path.home()`, `os.getcwd()`, `sys.prefix`, `os.environ`) is
computed at module scope.
- [ ] Every `env` / `this` / `root` use in `commands()` carries `# noqa: F821` if the repo lints
`package.py`.
- [ ] No `env`, `this` or `root` is defined at module scope to "satisfy" a linter.
- [ ] `rez-build --install` exits 0 **and** `rez-env <pkg>` resolves — a non-zero build may still
have written an install.
- [ ] After a serialization failure, `rez-search <pkg>` was used to check for a broken install, and
any that was found was removed before rebuilding.
## Agent workflow
1. Read the error's file path first: a `rez_write_*` temp path means the generated package, a
`packages_path` path means an already-installed one.
2. Grep the module scope of `package.py` for `import`, `class`, and anything that is not a literal
before suspecting the solver.
3. Move imports into `commands()`; move environment-dependent values into `commands()` too.
4. Check for a broken install left by the previous attempt (`rez-search <pkg>`), remove it if
present, then `rez-build --install`.
5. Confirm with `rez-env <pkg>` in a separate shell — a green build proves the file parses, not that
it resolves.
don't have the plugin yet? install it then click "run inline in claude" again.
package.py pitfallsrez executes package.py once at build time and serializes every surviving module-level name back to the installed package.py as text. this means anything at module scope that isn't a plain value, function, or module gets written as invalid Python syntax or as names that no longer resolve. use this skill when a package resolve or build fails with a confusing error, when auditing a package.py for module-scope mistakes, or before releasing a package to production. covers rez 3.4.0 and the three-phase load/serialize/interpret execution model.
rez --version.<packages_path>/<name>/<version>/package.py.rez-build --install, rez-env, or a linter run. note whether the file path contains rez_write_ (temp) or the actual package path (installed).package.py file as a Python module on the build machine (or the machine running rez-env).env, this, root, base do not exist at this stage.input: raw package.py text. output: dict of module-level names and their runtime values.
rez-build --install or rez-release)commands, pre_commands, post_commands, pre_build_commands, pre_test_commands, preprocess, @early, @late), and strip any name starting with __.pformat() on its value to produce a text representation.package.py file in the install directory.timestamp (install time, by default) and format_version (always added by the filesystem package repository).input: dict of collected names and their values from phase 1. output: installed package.py file containing only serializable attributes as Python source text.
edge case: if pformat() produces invalid Python syntax (e.g. Path = <class 'pathlib.Path'>), the install is written anyway. the error only appears when phase 1 runs on a later resolve.
rez-env and all other resolve operations)package.py and parses it as Python.commands() function (and pre_commands, post_commands, etc. if present), not the module body.commands() execution, rez injects env (the rex environment object), this (the resolved package), root, and base into the local scope.commands() and writes shell code to the consumer's shell.input: installed package.py and the resolved package context. output: shell code and environment modifications.
edge case: phase 1 (the parse step) fails if the installed package.py syntax is invalid. the module body never runs, so no attribute is ever evaluated a second time by design.
if the error message file path contains rez_write_: the temp file is a rez-generated copy. the actual syntax error is in the installed copy (or would be if the install had succeeded). jump to pitfall 1 (top-level imports) or pitfall 2 (frozen module-scope values). do not edit the temp file.
if the error message file path contains the actual packages_path: an install was left behind by a previous rez-build --install run, even though it failed. jump to pitfall 4 (broken install). check rez-search <pkg> to confirm, then remove the directory and rebuild.
if the linter flags env, this, or root as undefined: these names are injected by rez at resolve time, not at module load time. they are legitimate in commands() but must carry # noqa: F821 if your linter runs. jump to pitfall 3. do not define these names at module scope.
if the error is invalid syntax: the installed package.py syntax is broken. a non-plain object (class, instance, compiled regex, etc.) was serialized as text. jump to pitfall 1. the repr() of that object is not valid Python.
if the error is NameError: name 're' is not defined (or similar) during resolve: the installed package.py parses but references a name that was stripped during serialization. a module was imported at module scope, its value was used at module scope, and the module itself was not written to the install. jump to pitfall 2. the value survives, the module it came from does not.
if rez-build --install succeeds but rez-env <pkg> fails: the build succeeded (phase 1 and 2 on the build machine), but phase 1 on the resolve machine (or CI environment) fails. the installed package.py has a syntax or name error from pitfall 1 or 2. rebuild after fixing the source, delete the broken install if present, and test resolve in a fresh shell.
on success:
rez-build --install exits 0.package.py in <packages_path>/<name>/<version>/ contains only module-level attributes that parse as valid Python and that do not reference stripped modules.rez-env <pkg> resolves without error in a separate shell session (not the build shell).rez-context --so prints a valid resolved context with the package present.on failure (pitfall 1 or 2):
rez-build --install exits non-zero with ResourceError: Problem loading <rez_write_*>/package.py: <reason>.invalid syntax if a class or instance object was serialized, or NameError if a stripped module was referenced.packages_path (the error happens during build environment resolution, before the install step).on failure (pitfall 4):
rez-build --install exits non-zero with ResourceError: Problem loading <packages_path>/<name>/<version>/package.py: <reason>.you know the skill worked when:
package.py (the original source, not the generated temp or installed file).commands() or into @late().rez-build --install exits 0 and prints no warnings about serialization.rez-env <pkg> resolves in a fresh shell, confirming the installed package.py parses and executes.rez-context --so shows the package as resolved with correct attributes (no extra classes or junk serialized from module scope).| phase | when | what happens to package.py |
|---|---|---|
| load | every rez read (resolve, build, search) | executes the file; collects all module-level names as candidates |
| serialize | on rez-build --install or rez-release |
writes surviving attributes back as Python source into the install |
| interpret | on rez-env and resolve |
parses the installed file; runs commands() only, with injected env/this/root; does not re-run module body |
key insight: module body is Python evaluated on the builder's machine. commands() is rex interpreted on the consumer's machine. never mix them.
from x import SomeClass breaks the installed packagerez-build --install fails while resolving the build environment, before your build command runs. the error message names a temp file like C:\Users\<user>\AppData\Local\Temp\rez_write__epzwl2x\package.py.
a module-level name is bound to something that is not a plain value, function, module, or __-name. the most common case is importing a class:
from pathlib import Path
documents_path = Path.home().as_posix() + "/Documents/.p4config"
name = "foo"
version = "1.0.0"
Path is a class object. rez serializes it by calling pformat(), which produces:
Path = <class 'pathlib.Path'>
this is not valid Python syntax. during the next phase 1 on any resolve, parsing fails with invalid syntax.
Resolving build environment:
resolved by builder@BUILD-HOST, on Fri Oct 02 01:05:17 2026, using Rez v3.4.0
...
01:05:17 ERROR ResourceError: Problem loading C:\Users\<user>\AppData\Local\Temp\rez_write__epzwl2x\package.py: invalid syntax (package.py, line 12)
move the import into commands(). keep imports and objects out of module scope entirely:
name = "foo"
version = "1.0.0"
def commands():
# Import inside commands() so it is not captured as a package attribute.
# Rez serializes module-level names into the installed package.py, and a
# class object renders as invalid syntax.
from pathlib import Path
documents_path = Path.home().as_posix() + "/Documents/.p4config"
env.P4CONFIG.set(documents_path)
the installed package.py now contains only name, version, commands, plus rez-added timestamp and format_version. no class, instance, or module appears.
a package works on the builder's machine and fails everywhere else. paths point to the builder's home, hostnames or sys.prefix values are from the build machine, etc.
anything environment-dependent is computed at module scope:
import sys
from pathlib import Path
sys_path = sys.prefix
documents_path = Path.home().as_posix() + "/Documents/.p4config"
phase 1 runs on the builder's machine. the results are written to the install:
sys_path = 'C:\\Users\\<builder>\\AppData\\Local\\Programs\\Python\\Python312'
documents_path = 'C:/Users/<builder>/Documents/.p4config'
note: sys is stripped (it's a module), but sys_path survives as a string. the value is frozen; the module it came from is not. phase 1 on the consumer's machine never re-computes it.
move anything that depends on who runs the resolve or where it runs into commands():
def commands():
from pathlib import Path
env.P4CONFIG.set(Path.home().as_posix() + "/Documents/.p4config")
use @early() only for values that are genuinely a property of the package (version, requires, etc.), not a property of the build machine.
@early() and @late()these decorators run at module scope on every resolve. they are not safer than module scope itself , environment-dependent code belongs in commands(), not in @early() or @late().
env, this, and root are undefined names to lintersyour editor or CI linter flags env, this, or root as undefined, even though the package works in rez.
rez injects these names only during phase 3 (interpret), inside the commands() scope. they do not exist when the file is parsed as ordinary Python. env is the rex environment object; this is the resolved package; root and base are path variables.
F821 Undefined name `env`
--> package.py:6:5
|
5 | def commands():
6 | env.PYTHONPATH.prepend("{this.root}/site-packages")
| ^^^
silence the linter at the point of use:
def commands():
env.PYTHONPATH.prepend("{this.root}/site-packages") # noqa: F821
env.RESOURCE_PATH.prepend("{this.root}/resource") # noqa: F821
this documents the intent and suppresses false positives.
do not define env or root at module scope to satisfy the linter. that creates real package attributes that get serialized (triggering pitfalls 1 and 2).
you fix package.py, rebuild, and the same error comes back , now named in the installed package.py path, not a temp file.
a failed rez-build --install can leave a package behind, depending on when the failure occurs. a failure during build environment resolution (pitfall 1) happens before the install step, so nothing is written. a failure during or after the install step leaves the payload in place. on the next resolve, rez tries to read the broken install, hits the same syntax or name error, and fails again , even though you fixed the source.
check whether a broken install exists:
rez-search foo
if it is listed, remove it and rebuild:
rm -rf <packages_path>/foo/1.0.0
rez-build --install
verify the fix in a fresh shell, not in the build shell:
rez-env foo
rez-context --so
the build may exit 0 without writing an install (if the error is early), so always verify that rez-env resolves, not just that the build succeeded.
tested on rez 3.4.0 by executing each snippet and dumping the installed form:
| module-level statement | survives | written as | result |
|---|---|---|---|
import sys |
no | , | stripped |
sys_path = sys.prefix |
yes | 'C:\\Users\\<user>\\...\\Python312' |
frozen on builder |
from os.path import join |
no | , | stripped |
def _helper(): ... |
no | , | stripped |
from pathlib import Path |
yes | Path = <class 'pathlib.Path'> |
invalid syntax on parse |
class Helper: ... |
yes | Helper = <class 'Helper'> |
invalid syntax on parse |
my_re = re.compile(r'foo-\d+') |
yes | my_re = re.compile('foo-\\d+') |
NameError on execute (re is gone) |
my_const = 'hello' |
yes | 'hello' |
normal attribute, correct use |
the survival rule: rez strips modules, functions (except the special ones), and __-names. everything else stays. two failure modes exist:
repr() is not valid Python. fails during phase 1 parsing with invalid syntax.repr() is valid Python but names a stripped module. parses fine, fails during phase 1 execution with NameError: name 're' is not defined.both reach you as ResourceError: Problem loading <path>: <reason>. read the reason, not just the exception type.
commands() or inside @late() only.Path.home(), os.getcwd(), sys.prefix, os.environ) is computed at module scope.env / this / root / base use in commands() carries # noqa: F821 if the repo lints package.py.env, this, root, or base is defined at module scope to satisfy a linter.rez-build --install exits 0 and rez-env <pkg> resolves in a fresh shell. a non-zero build may still have written an install.rez-search <pkg> was run to check for a broken install, and any that was found was removed before rebuilding.rez_write_* temp path means the error is in the generated package. a packages_path path means a broken install was left behind.package.py for import, class, and any name that is not a