Reviewer · Performance Optimization
Defer heavy imports
Never import costly or optional third-party dependencies (e.g. `litellm`, `mcp`) at module level if they slow down package import or trigger side effects such as network calls. Move the import inside the function or method that actually needs it, or, for type-only references, guard it with `if TYPE_CHECKING:`. If the symbol is used repeatedly and...
Never import costly or optional third-party dependencies (e.g. litellm, mcp) at module level if they slow down package import or trigger side effects such as network calls. Move the import inside the function or method that actually needs it, or, for type-only references, guard it with if TYPE_CHECKING:. If the symbol is used repeatedly and re-importing on every call would add overhead, cache it once in a module-level global guarded by an is None check so the import happens only on first real use, while still allowing tests to monkeypatch the attribute. This keeps import package fast and side-effect free without changing any call-site behavior or signatures.
Example pattern:
# Bound on first real use, not at module import time.
completion = None
def _bind_litellm() -> None:
global completion
if completion is None:
from litellm import completion as _completion
completion = _completion
def call_llm(...):
_bind_litellm()
return completion(...)
For type-checking-only usages:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from mcp import ClientSession
Measure the impact (e.g. import time before/after) when deferring imports to confirm the optimization is real and justified, and document why the import was deferred so static analyzers that can’t resolve the dependency in their own environment aren’t mistaken for real regressions.