{"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/c0ef574e29109210e96e652771ae4e7b88615fa4/aiohttp/helpers.py#L899-L935","documentation":"Raised by BaseKey.__init__ when the frame-walk to find an enclosing '<module>' frame fails, i.e. no module-level frame exists on the call stack when an AppKey/RequestKey/ResponseKey is instantiated. The prefix requires a module name to deduplicate keys; without it, construction is refused (RuntimeError).","triggerScenarios":"Instantiating AppKey() from within a C extension frame, an exec/eval with no globals['__name__'], or in an environment where inspect.currentframe()/f_back is None (restricted or patched interpreters). In normal module-level or function-level code this never fires.","commonSituations":"Building keys dynamically via exec(); sandboxed environments stripping frames; unusual interpreters (PyPy edge cases) where f_back chains differ.","solutions":["Define keys at module top level so a '<module>' frame is reachable.","Avoid constructing keys inside exec/eval; import a module that declares them.","If unavoidable, factor key creation into a normal imported function."],"exampleFix":"// before\nexec(\"key = AppKey('x')\")\n// after\n# in myapp/keys.py\nfrom aiohttp import AppKey\nkey = AppKey('x')","handlingStrategy":"validation","validationCode":"import inspect\ndef can_resolve_module():\n    frame = inspect.currentframe()\n    while frame:\n        if frame.f_code.co_name == '<module>' and '__name__' in frame.f_globals:\n            return True\n        frame = frame.f_back\n    return False","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Declare AppKey instances at module top level.","Avoid constructing keys inside exec/eval.","Import key-defining modules rather than synthesizing them at runtime."],"tags":["appkey","asyncio","internals","module"],"analyzedSha":"c0ef574e29109210e96e652771ae4e7b88615fa4","analyzedAt":"2026-08-04T19:51:05.467Z","schemaVersion":2}