Reviewer · Null Handling
Guard nullable attribute access
Many bugs in this codebase come from treating an attribute, property, or parameter as always-present when it is actually `Optional` or may not exist yet (partially constructed objects, duck-typed targets, provider responses, dict-vs-object shapes). Apply these defensive patterns consistently:
Many bugs in this codebase come from treating an attribute, property, or parameter as always-present when it is actually Optional or may not exist yet (partially constructed objects, duck-typed targets, provider responses, dict-vs-object shapes). Apply these defensive patterns consistently:
-
Use
getattr(obj, "attr", default)instead ofobj.attrwhenever the attribute may be missing or the object may be partially initialized. This applies to duck-typed checks (callable(getattr(target, "short_memory_init", None))), properties that delegate to lazily-created instance state (guard withgetattr(self, "autonomous_loop", None)before it’s built in__init__), and nested object graphs (getattr(self.knowledge_generator, "agent", None)). - When a value typed
Optional[X]must be passed to an API expectingX, supply an explicit fallback rather than lettingNoneflow through:conversation.add(content=agent_answer(agent, result), role=agent.agent_name or "Worker") messages_for(current_agent.agent_name or "", ...) - For attribute narrowing across function/method calls (e.g. Pyre/type-checkers don’t narrow
self.optional_pathafter anos.path.existscall), bind the optional attribute to a local variable first, then narrow and reuse the local:path = self.memory_md_path if path and os.path.exists(path): size = os.path.getsize(path) -
Don’t trust that a value exists just because a key is present — validate its type before using it numerically or otherwise (
isinstance(value, (int, float))before summing), and avoidsetdefault-style “only set if absent” logic when the real intent is “only set if falsy/empty”. -
Keep type annotations honest: if a parameter’s default is
None, annotate itOptional[T] = None, notT = None. This keeps static analysis useful instead of masking real nullability. - Avoid relying on an incidental
None/non-Nonevalue as a proxy for program state (e.g. “transcript is None means first loop”); prefer an explicit, named condition so future edits to the surrounding code can’t silently break the null-based assumption.
Applying these patterns prevents AttributeError/TypeError crashes in properties, finalizers, and finally blocks, and keeps optional/nullable data flowing safely through the system instead of failing silently or hard-crashing downstream.