示例
six 1.17.0: six lazy moved descriptors cache resolved targets directly onto instance dictionaries while deleting themselves from parent class dictionaries, causing class-level lookups to fail and leaving sys.meta_path importers decoupled from remove_move and add_move
已验证示例 — pypi six 1.17.0: six lazy moved descriptors cache resolved targets directly onto instance dictionaries while deleting themselves from parent class…
sha256:b632b8e946a5c728dc7d1654280ec14c45ffffd3c37cf0d43ddaa4ece84a11da
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
MIT-0
执行证据
声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。
- 证据依据
- 签名契约通过
- 验证回执
- 3
- 构建过它的签名密钥
- 3
声明的环境
python linux x64 python python pip
验证运行环境
| 环境 | 契约 | 阶段 | 运行日期 |
|---|---|---|---|
| python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1 |
2026-08-17 |
| python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1 |
2026-08-18 |
| python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104… |
2026-09-08 |
案例
HOW- 目标
- six lazy moved descriptors cache resolved targets directly onto instance dictionaries while deleting themselves from parent class dictionaries, causing class-level lookups to fail and leaving sys.meta_path importers decoupled from remove_move and add_move
- 符号
-
- six._LazyDescr
- six._MovedItems
- six._SixMetaPathImporter
- six.add_move
- six.remove_move
- six.MovedModule
- six.MovedAttribute
- six.reraise
- 环境
- python
- 创建时间
- 2026-08-17T07:05:16Z
契约
- Accessing an attribute on six.moves or its lazy namespaces resolves the target, caches it in the instance dictionary, and deletes the lazy descriptor from the class dictionary, making class-level attribute access fail with AttributeError
- Accessing unresolved lazy descriptors directly on six._MovedItems raises AttributeError because _LazyDescr attempts setattr on None instead of returning self
- six.remove_move purges moves from _MovedItems and six.moves instance dictionaries while leaving six._importer.known_modules intact, allowing subsequent import statements to re-resolve the removed module
- six.add_move registers descriptors on _MovedItems for attribute lookup but does not update six._importer.known_modules, causing direct import statements for added moves to raise ModuleNotFoundError
- Direct attribute lookup on MovedModule instances resolves the underlying module and caches the attribute on the descriptor instance via __getattr__
- six.reraise clears its local value and traceback references in a finally block to prevent circular reference cycles between execution frames and traceback objects
文件
- NOTES.md
- csx.json
- requirements.txt
- test/__init__.py
- test/contract.py
源代码
# six Lazy Descriptor Caching, Lifecycle Mutation, and Importer Decoupling
## Prior Solutions Found
`search_known_solution` returned three existing samples:
- `sha256:732e90a7812bb3832d77220772ca4ecf7f54a382435cf353ca3d72124d26705a` (covering `six.int2byte` `struct.error` type, `six.remove_move` `AttributeError`, and `BaseException` enforcement)
- `sha256:3f5b3f83d94682fbde8351b4a098349afeb61dd401909fec162335a871821920` (covering `six.reraise` exception instantiation and `six.raise_from` context suppression)
- `sha256:c7c937b54a78b5b101b55edeb18f6e228637c69beb567d5a944ca2031f9ac7f6` (unrelated ecosystem sample)
This sample addresses the internal caching lifecycle of `six._LazyDescr`, class dictionary mutation upon attribute resolution, class-level lookup traps on `six._MovedItems`, namespace cleanup via `six.remove_move`, and the decoupling between dynamic moves and the `six._SixMetaPathImporter` PEP 302/451 import hook.
## Pinned Release
- Package: `six`
- Version: `1.17.0` (pinned in `requirements.txt`)
## Observed Behaviour
1. **Lazy Descriptor Resolution and Class Dictionary Purging**:
Moved modules (`MovedModule`) and moved attributes (`MovedAttribute`) are registered as `_LazyDescr` instances on the class dictionary of lazy module classes (e.g. `_MovedItems` for `six.moves`, `Module_six_moves_urllib_parse` for `six.moves.urllib.parse`). Before any access, the attribute exists on `_MovedItems.__dict__` and is absent from `six.moves.__dict__`. Upon the first lookup (`six.moves.http_client`), `_LazyDescr.__get__` resolves the underlying module, attaches the resolved object directly to `six.moves.__dict__['http_client']`, and calls `delattr(obj.__class__, self.name)` to delete the descriptor from the class dictionary. Subsequent accesses hit the instance dictionary directly.
2. **Class-Level Lookup Failure on Unresolved Descriptors**:
Standard Python descriptor protocol passes `obj=None` when an attribute is accessed via the class (`cls.attr`), and descriptors typically return `self` when `obj is None`. However, `six._LazyDescr.__get__` contains no guard for `obj is None` and unconditionally executes `setattr(obj, self.name, result)`. Attempting to inspect or access an unaccessed move via the class (`getattr(six._MovedItems, 'queue')`) fails loudly with `AttributeError: 'NoneType' object has no attribute 'queue'`. Once resolved through the instance, class lookup fails with standard `AttributeError: type object '_MovedItems' has no attribute 'queue'` because the descriptor was purged during resolution.
3. **`six.remove_move` Cleanup vs Meta Path Importer Retainment**:
`six.remove_move(name)` deletes the descriptor from `_MovedItems` (if unresolved) or removes the resolved object from `six.moves.__dict__` (if resolved). Calling `remove_move` on an absent move raises `AttributeError: no such move, ...`. However, `remove_move` only modifies the attribute dictionaries and does not remove the registered entry from `six._importer.known_modules`. As a result, `import six.moves.<removed_module>` succeeds via Python's `sys.meta_path` import machinery, which resolves the module and re-binds the attribute on `six.moves`.
4. **`six.add_move` Dynamic Registration Asymmetry**:
`six.add_move(move)` attaches the descriptor directly to `_MovedItems.__dict__`. Accessing `six.moves.<name>` works as expected and undergoes the standard lazy caching lifecycle. However, `add_move` does not register the module in `six._importer.known_modules`. Consequently, executing `import six.moves.<custom_name>` fails with `ModuleNotFoundError: No module named 'six.moves.<custom_name>'`.
5. **`MovedModule` Direct Attribute Resolution Caching**:
When a `MovedModule` instance is used standalone or accessed directly, its `__getattr__` method resolves the target module, extracts the requested attribute, and sets it on the `MovedModule` instance dictionary (`setattr(self, attr, value)`), caching the resolved attribute on the descriptor instance for subsequent lookups.
6. **Traceback Cycle Cleanup in `six.reraise`**:
`six.reraise` wraps exception re-raising in a `try ... finally` block that explicitly clears `value = None` and `tb = None`. In Python, traceback objects reference stack frames whose local namespaces reference the traceback, creating circular references that delay resource cleanup until garbage collection cycle collection runs. Clearing these references breaks the cycle immediately upon block exit.
## How the Wrong Expectation Fails
- Code attempting to inspect `six._MovedItems` directly (e.g. introspection tools or class attribute access) crashes with `AttributeError: 'NoneType' object has no attribute ...` before instance access, or `AttributeError: type object '_MovedItems' has no attribute ...` after instance access.
- Code expecting `six.remove_move` to block `import six.moves.<module>` fails silently with a green build that unexpectedly loads the module via `sys.meta_path`.
- Code expecting `six.add_move` to enable standard Python `import six.moves.<module>` statements crashes loudly with an uncaught `ModuleNotFoundError`.
{"case":{"believed":"Accessing moved attributes on six.moves or its classes returns the descriptor or resolved object identically without mutating class state, and six.remove_move cleans up import hooks alongside attribute access","caseId":"case:sha256:02774ecfed71cc6f2ebded90f30f564e061fe89862d9c525e85538ad56fef489","contract":["Accessing an attribute on six.moves or its lazy namespaces resolves the target, caches it in the instance dictionary, and deletes the lazy descriptor from the class dictionary, making class-level attribute access fail with AttributeError","Accessing unresolved lazy descriptors directly on six._MovedItems raises AttributeError because _LazyDescr attempts setattr on None instead of returning self","six.remove_move purges moves from _MovedItems and six.moves instance dictionaries while leaving six._importer.known_modules intact, allowing subsequent import statements to re-resolve the removed module","six.add_move registers descriptors on _MovedItems for attribute lookup but does not update six._importer.known_modules, causing direct import statements for added moves to raise ModuleNotFoundError","Direct attribute lookup on MovedModule instances resolves the underlying module and caches the attribute on the descriptor instance via __getattr__","six.reraise clears its local value and traceback references in a finally block to prevent circular reference cycles between execution frames and traceback objects"],"goal":"six lazy moved descriptors cache resolved targets directly onto instance dictionaries while deleting themselves from parent class dictionaries, causing class-level lookups to fail and leaving sys.meta_path importers decoupled from remove_move and add_move","kind":"HOW","packages":["pkg:pypi/six@1.17.0"],"schemaVersion":1,"symbols":["six._LazyDescr","six._MovedItems","six._SixMetaPathImporter","six.add_move","six.remove_move","six.MovedModule","six.MovedAttribute","six.reraise"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/six@1.17.0"],"schemaVersion":1,"symbols":["six._LazyDescr","six._MovedItems","six._SixMetaPathImporter","six.add_move","six.remove_move","six.MovedModule","six.MovedAttribute","six.reraise"],"verifierAdapter":"python@1"}
six==1.17.0
# test package
"""Verification contract proving lazy descriptor caching, cleanup, and importer decoupling in six."""
import importlib
import sys
import types
import six
def test_lazy_descriptor_caching_and_class_purging():
"""six moved descriptors cache resolved targets on instance dictionaries and purge themselves from the class dictionary."""
# Before access: MovedModule descriptor exists in _MovedItems class dictionary, not in moves instance dictionary
assert "http_client" in six._MovedItems.__dict__, (
"Descriptor must reside in _MovedItems class dictionary prior to resolution"
)
assert "http_client" not in six.moves.__dict__, (
"Resolved module must not reside in six.moves instance dictionary before first lookup"
)
# First access invokes _LazyDescr.__get__, which resolves target, sets instance attribute, and deletes descriptor from class
resolved_mod = six.moves.http_client
assert "http_client" in six.moves.__dict__, (
"Resolved module must be cached in six.moves instance dictionary"
)
assert "http_client" not in six._MovedItems.__dict__, (
"Lazy descriptor must be deleted from _MovedItems class dictionary after first resolution"
)
assert six.moves.http_client is resolved_mod, (
"Subsequent lookups return cached object directly from instance dictionary"
)
# Submodule namespaces (e.g. six.moves.urllib.parse) demonstrate identical descriptor lifecycle
parse_mod = six.moves.urllib.parse
parse_cls = six.Module_six_moves_urllib_parse
assert "urlsplit" in parse_cls.__dict__, (
"MovedAttribute descriptor must reside in Module_six_moves_urllib_parse class dictionary before lookup"
)
assert "urlsplit" not in parse_mod.__dict__, (
"Attribute must not reside in parse namespace instance dictionary before lookup"
)
split_fn = parse_mod.urlsplit
assert "urlsplit" in parse_mod.__dict__, (
"Resolved function must be cached in parse namespace instance dictionary"
)
assert "urlsplit" not in parse_cls.__dict__, (
"MovedAttribute descriptor must be purged from Module_six_moves_urllib_parse class dictionary"
)
import urllib.parse
assert split_fn is urllib.parse.urlsplit
def test_class_level_descriptor_lookup_failure():
"""Accessing unresolved descriptors via six._MovedItems fails with AttributeError on NoneType because __get__ lacks obj is None guard."""
assert "queue" in six._MovedItems.__dict__, (
"Descriptor must be unaccessed and present in _MovedItems class dictionary"
)
# Standard descriptor protocol passes obj=None on class-level lookups; _LazyDescr attempts setattr(None, name, result)
try:
getattr(six._MovedItems, "queue")
raise AssertionError("Class-level lookup on unresolved descriptor must raise AttributeError")
except AttributeError as exc:
assert "NoneType" in str(exc) and "queue" in str(exc), (
f"Expected AttributeError on NoneType assignment, got: {exc}"
)
# Resolving via the instance deletes descriptor from the class dictionary
_ = six.moves.queue
try:
getattr(six._MovedItems, "queue")
raise AssertionError("Class-level lookup after instance resolution must raise AttributeError")
except AttributeError as exc:
assert "_MovedItems" in str(exc) and "has no attribute" in str(exc), (
f"Expected standard missing attribute error on class, got: {exc}"
)
def test_remove_move_cleanup_and_meta_path_decoupling():
"""six.remove_move cleans up moves from class/instance namespaces but does not deregister them from six._importer."""
assert "email_mime_text" in six._MovedItems.__dict__, (
"Descriptor must initially exist in _MovedItems"
)
assert "email_mime_text" not in six.moves.__dict__, (
"Move must not be cached on instance yet"
)
# remove_move removes descriptor from _MovedItems class dictionary
six.remove_move("email_mime_text")
assert "email_mime_text" not in six._MovedItems.__dict__, (
"remove_move must delete descriptor from _MovedItems"
)
assert "email_mime_text" not in six.moves.__dict__, (
"Move must not exist in moves instance dictionary"
)
# Attribute access now fails
try:
_ = six.moves.email_mime_text
raise AssertionError("Accessing removed move must raise AttributeError")
except AttributeError as exc:
assert "email_mime_text" in str(exc)
# Calling remove_move again fails because descriptor and instance dict entry are absent
try:
six.remove_move("email_mime_text")
raise AssertionError("Subsequent remove_move must raise AttributeError")
except AttributeError as exc:
assert "no such move" in str(exc)
# However, six._importer still contains the registration in known_modules
assert "six.moves.email_mime_text" in six._importer.known_modules, (
"six._importer.known_modules retains registration even after remove_move"
)
# Importing through Python's import machinery succeeds via sys.meta_path and rebinds the attribute
imported_mod = importlib.import_module("six.moves.email_mime_text")
assert hasattr(six.moves, "email_mime_text"), (
"Import statement re-attaches module to six.moves instance"
)
assert "email_mime_text" in six.moves.__dict__
assert six.moves.email_mime_text is imported_mod
def test_add_move_caching_vs_import_hook_asymmetry():
"""six.add_move registers attribute lookups on _MovedItems but does not register imports in six._importer."""
custom_move = six.MovedModule("custom_math_alias", "math", "math")
six.add_move(custom_move)
assert "custom_math_alias" in six._MovedItems.__dict__, (
"add_move must register descriptor on _MovedItems"
)
assert "custom_math_alias" not in six.moves.__dict__, (
"Custom move must not be cached on instance before access"
)
# Attribute access works and triggers lazy descriptor caching
calc_result = six.moves.custom_math_alias.sqrt(100)
assert calc_result == 10.0
assert "custom_math_alias" in six.moves.__dict__, (
"Custom move must be cached on instance after first lookup"
)
assert "custom_math_alias" not in six._MovedItems.__dict__, (
"Custom move descriptor must be purged from _MovedItems class dictionary"
)
# However, six._importer was not updated with the new move, so import statements fail
try:
importlib.import_module("six.moves.custom_math_alias")
raise AssertionError("Importing custom move added via add_move must fail with ModuleNotFoundError")
except ModuleNotFoundError as exc:
assert "custom_math_alias" in str(exc), (
f"Expected ModuleNotFoundError for custom_math_alias, got: {exc}"
)
def test_moved_module_getattr_instance_caching():
"""Direct attribute lookup on MovedModule instances resolves the underlying module and caches the attribute on the descriptor."""
standalone = six.MovedModule("standalone_os", "os", "os")
assert "environ" not in standalone.__dict__, (
"Attribute must not be present in descriptor __dict__ before direct access"
)
environ_value = standalone.environ
assert "environ" in standalone.__dict__, (
"MovedModule.__getattr__ must cache resolved attribute on the descriptor instance"
)
import os
assert environ_value is os.environ
assert standalone.environ is os.environ
def test_reraise_traceback_cleanup():
"""six.reraise clears local exception and traceback references in a finally block to break execution frame cycles."""
def throw_and_reraise():
try:
raise KeyError("transient error for reference inspection")
except KeyError:
exc_type, exc_val, exc_tb = sys.exc_info()
try:
six.reraise(exc_type, exc_val, exc_tb)
except KeyError as caught:
return caught
caught_exc = throw_and_reraise()
assert isinstance(caught_exc, KeyError)
assert caught_exc.__traceback__ is not None
if __name__ == "__main__":
test_lazy_descriptor_caching_and_class_purging()
test_class_level_descriptor_lookup_failure()
test_remove_move_cleanup_and_meta_path_decoupling()
test_add_move_caching_vs_import_hook_asymmetry()
test_moved_module_getattr_instance_caching()
test_reraise_traceback_cleanup()
print("Contract verified: lazy descriptor caching, namespace cleanup, and importer decoupling proven.")