{"record":{"id":"c621674be4312672","repo":"astral-sh/uv","slug":"you-must-use-import-runpy-runpy-run-path-this-fil","errorCode":null,"errorMessage":"You must use import runpy; runpy.run_path(this_file)","messagePattern":"You must use import runpy; runpy\\.run_path\\(this_file\\)","errorType":"exception","errorClass":"AssertionError","httpStatus":null,"severity":"error","filePath":"crates/uv-virtualenv/src/activator/activate_this.py","lineNumber":41,"sourceCode":"Activate virtualenv for current interpreter:\n\nimport runpy\nrunpy.run_path(this_file)\n\nThis can be used when you must use an existing Python interpreter, not the virtualenv bin/python.\n\"\"\"  # noqa: D415\n\nfrom __future__ import annotations\n\nimport os\nimport site\nimport sys\n\ntry:\n    abs_file = os.path.abspath(__file__)\nexcept NameError as exc:\n    msg = \"You must use import runpy; runpy.run_path(this_file)\"\n    raise AssertionError(msg) from exc\n\nbin_dir = os.path.dirname(abs_file)\nbase = bin_dir[: -len(\"{{ BIN_NAME }}\") - 1]  # strip away the bin part from the __file__, plus the path separator\n\n# prepend bin to PATH (this file is inside the bin directory)\nos.environ[\"PATH\"] = os.pathsep.join([bin_dir, *os.environ.get(\"PATH\", \"\").split(os.pathsep)])\nos.environ[\"VIRTUAL_ENV\"] = base  # virtual env is right above bin directory\nos.environ[\"VIRTUAL_ENV_PROMPT\"] = \"{{ VIRTUAL_PROMPT }}\" or os.path.basename(base)  # noqa: SIM222\n\n# add the virtual environments libraries to the host python import mechanism\nprev_length = len(sys.path)\nfor lib in \"{{ RELATIVE_SITE_PACKAGES }}\".split(os.pathsep):\n    path = os.path.realpath(os.path.join(bin_dir, lib))\n    site.addsitedir(path)\nsys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length]\n\nsys.real_prefix = sys.prefix\nsys.prefix = base","sourceCodeStart":23,"sourceCodeEnd":59,"githubUrl":"https://github.com/astral-sh/uv/blob/f1a42680ff5272232d65748acf338b19778dde24/crates/uv-virtualenv/src/activator/activate_this.py#L23-L59","documentation":"`activate_this.py` is the template uv-virtualenv writes into `<venv>/bin/` for in-process activation. It computes `base` from `__file__`, so it must run as a file, not as a bare code string. The `try: abs_file = os.path.abspath(__file__)` catches the NameError raised when `__file__` is undefined and re-raises it as an AssertionError telling you the supported invocation: `runpy.run_path(this_file)`.","triggerScenarios":"Executing the script via `exec(open(\".../activate_this.py\").read())` (the snippet from virtualenv's docs) against a uv-created venv: `exec` compiles the code without a filename, so `__file__` is never bound and the NameError handler fires. Also `compile()`+`eval()` of the file contents, or any embedding that passes source text instead of a path.","commonSituations":"IDE run-configurations and PyCharm-style activation tasks, bootstrap scripts copied from virtualenv documentation, tox/nox activation helpers, or embedding code that activates a venv in-process; these worked with old virtualenv builds (which tolerated exec) but hit the explicit assertion with uv venvs.","solutions":["Use runpy so `__file__` is defined: `import runpy; runpy.run_path(\"/path/to/.venv/bin/activate_this.py\")`.","Prefer out-of-process activation (`source .venv/bin/activate` or `uv run`) when you control the shell.","If you must exec source text, pass a filename: `exec(compile(source, activate_path, \"exec\"), {\"__file__\": activate_path})`."],"exampleFix":"# before\nexec(open(\"/path/to/.venv/bin/activate_this.py\").read())\n# AssertionError: You must use import runpy; runpy.run_path(this_file)\n\n# after\nimport runpy\nrunpy.run_path(\"/path/to/.venv/bin/activate_this.py\")","handlingStrategy":"validation","validationCode":"def activate_venv_inprocess(activate_this: str) -> None:\n    # Reject exec-based activation before it fails cryptically\n    import os\n    assert os.path.isfile(activate_this), f\"missing {activate_this}\"\n    import runpy\n    runpy.run_path(activate_this)  # defines __file__ correctly","typeGuard":"def is_runpy_safe() -> bool:\n    \"\"\"True when __file__ is defined, i.e. run via run_path/run_module rather than exec(code).\"\"\"\n    return \"__file__\" in globals()","tryCatchPattern":"try:\n    exec(compile(source, path, \"exec\"), {\"__file__\": path})\nexcept (AssertionError, NameError) as exc:\n    if \"runpy\" in str(exc):\n        import runpy\n        runpy.run_path(path)\n    else:\n        raise","preventionTips":["Standardize on `import runpy; runpy.run_path(venv_bin / \"activate_this.py\")` in all activation helpers.","Search your tooling for `activate_this` + `exec(` and replace before upgrading to uv-created venvs.","Where possible, avoid in-process activation entirely: use `uv run` or subprocesses with the venv's interpreter."],"tags":["virtualenv","activation","runpy","python","embedding"],"backgroundTag":null,"analyzedSha":"f1a42680ff5272232d65748acf338b19778dde24","analyzedAt":"2026-08-16T04:51:47.599Z","schemaVersion":2},"datasetVersion":"2026-08-16T08:17:34.114Z"}