{"record":{"id":"d2ab7dbde436ea50","repo":"aio-libs/aiohttp","slug":"failed-to-get-module-name","errorCode":null,"errorMessage":"Failed to get module name.","messagePattern":"Failed to get module name\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"aiohttp/helpers.py","lineNumber":917,"sourceCode":"\n    __slots__ = (\"_name\", \"_t\", \"__orig_class__\")\n\n    # This may be set by Python when instantiating with a generic type. We need to\n    # support this, in order to support types that are not concrete classes,\n    # like Iterable, which can't be passed as the second parameter to __init__.\n    __orig_class__: type[object]\n\n    # TODO(PY314): Change Type to TypeForm (this should resolve unreachable below).\n    def __init__(self, name: str, t: type[_T] | None = None):\n        # Prefix with module name to help deduplicate key names.\n        frame = inspect.currentframe()\n        while frame:\n            if frame.f_code.co_name == \"<module>\":\n                module: str = frame.f_globals[\"__name__\"]\n                break\n            frame = frame.f_back\n        else:\n            raise RuntimeError(\"Failed to get module name.\")\n\n        # https://github.com/python/mypy/issues/14209\n        self._name = module + \".\" + name  # type: ignore[possibly-undefined]\n        self._t = t\n\n    def __lt__(self, other: object) -> bool:\n        if isinstance(other, BaseKey):\n            return self._name < other._name\n        return True  # Order BaseKey above other types.\n\n    def __repr__(self) -> str:\n        t = self._t\n        if t is None:\n            with suppress(AttributeError):\n                # Set to type arg.\n                t = get_args(self.__orig_class__)[0]\n\n        if t is None:","sourceCodeStart":899,"sourceCodeEnd":935,"githubUrl":"https://github.com/aio-libs/aiohttp/blob/d041d4d0fd48c3f0832084d33be16cf1c4835f85/aiohttp/helpers.py#L899-L935","documentation":"BaseKey.__init__ raises RuntimeError when it cannot find a '<module>' frame in the call stack by walking frame.f_back. BaseKey (and its subclass AppKey) prefixes its internal name with the calling module's __name__ for deduplication. If instantiated from a context with no module-level frame (e.g. a deeply nested call where the module frame has been optimized away), the loop exits without breaking and the else clause fires.","triggerScenarios":"Creating an AppKey or BaseKey from a context where inspect.currentframe() and walking f_back cannot reach a frame with co_name == '<module>'. This can happen in certain REPL environments, eval/exec contexts, or when frame introspection is limited by the Python implementation (e.g. some JIT or restricted environments).","commonSituations":"Defining AppKey instances in interactive REPL sessions where the module frame structure differs; using exec() to dynamically define keys; running under Python implementations with limited frame support; deeply nested class bodies where frame walking misses the module frame.","solutions":["Define AppKey instances at module level in a .py file (the normal use case)","If using exec/eval, ensure the code object has a '<module>' frame by providing a proper __name__ in globals","Avoid creating AppKey dynamically in nested function calls — define them at module scope"],"exampleFix":"# before (dynamic creation may fail)\nkey = eval('AppKey(\"my_key\")')\n\n# after (module-level definition)\n# myapp/keys.py\nfrom aiohttp.web import AppKey\nmy_key = AppKey('my_key', str)","handlingStrategy":"validation","validationCode":"import inspect\n\ndef can_resolve_module_name() -> bool:\n    frame = inspect.currentframe()\n    while frame:\n        if frame.f_code.co_name == '<module>':\n            return True\n        frame = frame.f_back\n    return False\n\nif not can_resolve_module_name():\n    raise RuntimeError('Cannot create AppKey: no module frame in call stack')","typeGuard":null,"tryCatchPattern":"try:\n    my_key = AppKey('my_key', str)\nexcept RuntimeError as e:\n    if 'Failed to get module name' in str(e):\n        # Define at module level instead of dynamically\n        raise RuntimeError('AppKey must be defined at module level')\n    raise","preventionTips":["Always define AppKey instances at module scope in a .py file","Avoid creating keys in eval/exec/REPL contexts","Use a dedicated keys.py module for all AppKey definitions"],"tags":["app-key","introspection","runtime-error","application","initialization"],"backgroundTag":null,"analyzedSha":"d041d4d0fd48c3f0832084d33be16cf1c4835f85","analyzedAt":"2026-08-11T20:44:15.550Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}