Skip to content

venv --clear deletes symlink target contents before rejecting the symlink #158068

Open

Description

@frenzymadness

Bug report

Bug description:

ensure_directories() already refuses a symlinked or file-backed env_dir — but only in create_if_needed(), which runs after the clear step. With --clear / clear=True, the clear happens first and follows the symlink:

if os.path.exists(env_dir) and self.clear:   # exists() follows the symlink -> True
    self.clear_directory(env_dir)             # listdir() follows it -> wipes the TARGET's contents
...
create_if_needed(env_dir)                      # only now raises ValueError for the symlink

So if env_dir is a symlink to a real directory, clear_directory() deletes that directory's contents before venv rejects the path. This contradicts venv's own contract, which is to reject symlinked/file env_dir rather than act on it.

import venv, os, tempfile
base = tempfile.mkdtemp()
target = os.path.join(base, 'target'); os.mkdir(target)
open(os.path.join(target, 'sentinel.txt'), 'w').close()
link = os.path.join(base, 'env_link'); os.symlink(target, link)

print("before:", os.listdir(target))          # ['sentinel.txt']
try:
    venv.EnvBuilder(clear=True).ensure_directories(link)
except ValueError as e:
    print(type(e).__name__, e)                 # ValueError: Unable to create directory ...
print("after:", os.listdir(target))            # []  -- target already wiped

I'll try to propose a fix.

CPython versions tested on:

3.14

Operating systems tested on:

Linux

Linked PRs

Activity

  1. added
    type-bug
    on Sep 24, 2026
  2. added
    stdlib
    topic-venv
    on Sep 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibtopic-venvtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions