Skip to content

Commit 9649fa5

Browse files
committed
Treat the base Conda environment as a system environment (#7691)
Closes #7124 Closes #7137
1 parent e7cdae3 commit 9649fa5

File tree

4 files changed

+152
-23
lines changed

4 files changed

+152
-23
lines changed

crates/uv-python/src/discovery.rs

Lines changed: 34 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ use crate::microsoft_store::find_microsoft_store_pythons;
2626
#[cfg(windows)]
2727
use crate::py_launcher::{registry_pythons, WindowsPython};
2828
use crate::virtualenv::{
29-
conda_prefix_from_env, virtualenv_from_env, virtualenv_from_working_dir,
30-
virtualenv_python_executable,
29+
conda_environment_from_env, virtualenv_from_env, virtualenv_from_working_dir,
30+
virtualenv_python_executable, CondaEnvironmentKind,
3131
};
3232
use crate::{Interpreter, PythonVersion};
3333

@@ -179,6 +179,8 @@ pub enum PythonSource {
179179
ActiveEnvironment,
180180
/// A conda environment was active e.g. via `CONDA_PREFIX`
181181
CondaPrefix,
182+
/// A base conda environment was active e.g. via `CONDA_PREFIX`
183+
BaseCondaPrefix,
182184
/// An environment was discovered e.g. via `.venv`
183185
DiscoveredEnvironment,
184186
/// An executable was found in the search path i.e. `PATH`
@@ -227,27 +229,27 @@ pub enum Error {
227229
SourceNotAllowed(PythonRequest, PythonSource, PythonPreference),
228230
}
229231

230-
/// Lazily iterate over Python executables in mutable environments.
232+
/// Lazily iterate over Python executables in mutable virtual environments.
231233
///
232234
/// The following sources are supported:
233235
///
234236
/// - Active virtual environment (via `VIRTUAL_ENV`)
235-
/// - Active conda environment (via `CONDA_PREFIX`)
236237
/// - Discovered virtual environment (e.g. `.venv` in a parent directory)
237238
///
238239
/// Notably, "system" environments are excluded. See [`python_executables_from_installed`].
239-
fn python_executables_from_environments<'a>(
240+
fn python_executables_from_virtual_environments<'a>(
240241
) -> impl Iterator<Item = Result<(PythonSource, PathBuf), Error>> + 'a {
241-
let from_virtual_environment = std::iter::once_with(|| {
242+
let from_active_environment = std::iter::once_with(|| {
242243
virtualenv_from_env()
243244
.into_iter()
244245
.map(virtualenv_python_executable)
245246
.map(|path| Ok((PythonSource::ActiveEnvironment, path)))
246247
})
247248
.flatten();
248249

250+
// N.B. we prefer the conda environment over discovered virtual environments
249251
let from_conda_environment = std::iter::once_with(|| {
250-
conda_prefix_from_env()
252+
conda_environment_from_env(CondaEnvironmentKind::Child)
251253
.into_iter()
252254
.map(virtualenv_python_executable)
253255
.map(|path| Ok((PythonSource::CondaPrefix, path)))
@@ -265,7 +267,7 @@ fn python_executables_from_environments<'a>(
265267
})
266268
.flatten_ok();
267269

268-
from_virtual_environment
270+
from_active_environment
269271
.chain(from_conda_environment)
270272
.chain(from_discovered_environment)
271273
}
@@ -400,23 +402,35 @@ fn python_executables<'a>(
400402
})
401403
.flatten();
402404

403-
let from_environments = python_executables_from_environments();
405+
// Check if the the base conda environment is active
406+
let from_base_conda_environment = std::iter::once_with(|| {
407+
conda_environment_from_env(CondaEnvironmentKind::Base)
408+
.into_iter()
409+
.map(virtualenv_python_executable)
410+
.map(|path| Ok((PythonSource::BaseCondaPrefix, path)))
411+
})
412+
.flatten();
413+
414+
let from_virtual_environments = python_executables_from_virtual_environments();
404415
let from_installed = python_executables_from_installed(version, implementation, preference);
405416

406417
// Limit the search to the relevant environment preference; we later validate that they match
407418
// the preference but queries are expensive and we query less interpreters this way.
408419
match environments {
409420
EnvironmentPreference::OnlyVirtual => {
410-
Box::new(from_parent_interpreter.chain(from_environments))
421+
Box::new(from_parent_interpreter.chain(from_virtual_environments))
411422
}
412423
EnvironmentPreference::ExplicitSystem | EnvironmentPreference::Any => Box::new(
413424
from_parent_interpreter
414-
.chain(from_environments)
425+
.chain(from_virtual_environments)
426+
.chain(from_base_conda_environment)
427+
.chain(from_installed),
428+
),
429+
EnvironmentPreference::OnlySystem => Box::new(
430+
from_parent_interpreter
431+
.chain(from_base_conda_environment)
415432
.chain(from_installed),
416433
),
417-
EnvironmentPreference::OnlySystem => {
418-
Box::new(from_parent_interpreter.chain(from_installed))
419-
}
420434
}
421435
}
422436

@@ -611,8 +625,8 @@ fn satisfies_environment_preference(
611625
) -> bool {
612626
match (
613627
preference,
614-
// Conda environments are not conformant virtual environments but we treat them as such
615-
interpreter.is_virtualenv() || matches!(source, PythonSource::CondaPrefix),
628+
// Conda environments are not conformant virtual environments but we treat them as such.
629+
interpreter.is_virtualenv() || (matches!(source, PythonSource::CondaPrefix)),
616630
) {
617631
(EnvironmentPreference::Any, _) => true,
618632
(EnvironmentPreference::OnlyVirtual, true) => true,
@@ -1493,6 +1507,7 @@ impl PythonSource {
14931507
Self::Managed | Self::Registry | Self::MicrosoftStore => false,
14941508
Self::SearchPath
14951509
| Self::CondaPrefix
1510+
| Self::BaseCondaPrefix
14961511
| Self::ProvidedPath
14971512
| Self::ParentInterpreter
14981513
| Self::ActiveEnvironment
@@ -1505,6 +1520,7 @@ impl PythonSource {
15051520
match self {
15061521
Self::Managed | Self::Registry | Self::SearchPath | Self::MicrosoftStore => false,
15071522
Self::CondaPrefix
1523+
| Self::BaseCondaPrefix
15081524
| Self::ProvidedPath
15091525
| Self::ParentInterpreter
15101526
| Self::ActiveEnvironment
@@ -1826,6 +1842,7 @@ impl VersionRequest {
18261842
Self::Default => match source {
18271843
PythonSource::ParentInterpreter
18281844
| PythonSource::CondaPrefix
1845+
| PythonSource::BaseCondaPrefix
18291846
| PythonSource::ProvidedPath
18301847
| PythonSource::DiscoveredEnvironment
18311848
| PythonSource::ActiveEnvironment => Self::Any,
@@ -2217,7 +2234,7 @@ impl fmt::Display for PythonSource {
22172234
match self {
22182235
Self::ProvidedPath => f.write_str("provided path"),
22192236
Self::ActiveEnvironment => f.write_str("active virtual environment"),
2220-
Self::CondaPrefix => f.write_str("conda prefix"),
2237+
Self::CondaPrefix | Self::BaseCondaPrefix => f.write_str("conda prefix"),
22212238
Self::DiscoveredEnvironment => f.write_str("virtual environment"),
22222239
Self::SearchPath => f.write_str("search path"),
22232240
Self::Registry => f.write_str("registry"),

crates/uv-python/src/tests.rs

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -949,6 +949,74 @@ fn find_python_from_conda_prefix() -> Result<()> {
949949
"We should allow the active conda python"
950950
);
951951

952+
let baseenv = context.tempdir.child("base");
953+
TestContext::mock_conda_prefix(&baseenv, "3.12.1")?;
954+
955+
// But not if it's a base environment
956+
let result = context.run_with_vars(
957+
&[
958+
("CONDA_PREFIX", Some(baseenv.as_os_str())),
959+
("CONDA_DEFAULT_ENV", Some(&OsString::from("base"))),
960+
],
961+
|| {
962+
find_python_installation(
963+
&PythonRequest::Default,
964+
EnvironmentPreference::OnlyVirtual,
965+
PythonPreference::OnlySystem,
966+
&context.cache,
967+
)
968+
},
969+
)?;
970+
971+
assert!(
972+
matches!(result, Err(PythonNotFound { .. })),
973+
"We should not allow the non-virtual environment; got {result:?}"
974+
);
975+
976+
// Unless, system interpreters are included...
977+
let python = context.run_with_vars(
978+
&[
979+
("CONDA_PREFIX", Some(baseenv.as_os_str())),
980+
("CONDA_DEFAULT_ENV", Some(&OsString::from("base"))),
981+
],
982+
|| {
983+
find_python_installation(
984+
&PythonRequest::Default,
985+
EnvironmentPreference::OnlySystem,
986+
PythonPreference::OnlySystem,
987+
&context.cache,
988+
)
989+
},
990+
)??;
991+
992+
assert_eq!(
993+
python.interpreter().python_full_version().to_string(),
994+
"3.12.1",
995+
"We should find the base conda environment"
996+
);
997+
998+
// If the environment name doesn't match the default, we should not treat it as system
999+
let python = context.run_with_vars(
1000+
&[
1001+
("CONDA_PREFIX", Some(condaenv.as_os_str())),
1002+
("CONDA_DEFAULT_ENV", Some(&OsString::from("base"))),
1003+
],
1004+
|| {
1005+
find_python_installation(
1006+
&PythonRequest::Default,
1007+
EnvironmentPreference::OnlyVirtual,
1008+
PythonPreference::OnlySystem,
1009+
&context.cache,
1010+
)
1011+
},
1012+
)??;
1013+
1014+
assert_eq!(
1015+
python.interpreter().python_full_version().to_string(),
1016+
"3.12.0",
1017+
"We should find the conda environment"
1018+
);
1019+
9521020
Ok(())
9531021
}
9541022

crates/uv-python/src/virtualenv.rs

Lines changed: 47 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -57,15 +57,56 @@ pub(crate) fn virtualenv_from_env() -> Option<PathBuf> {
5757
None
5858
}
5959

60+
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
61+
pub(crate) enum CondaEnvironmentKind {
62+
/// The base Conda environment; treated like a system Python environment.
63+
Base,
64+
/// Any other Conda environment; treated like a virtual environment.
65+
Child,
66+
}
67+
68+
impl CondaEnvironmentKind {
69+
/// Whether the given `CONDA_PREFIX` path is the base Conda environment.
70+
///
71+
/// When the base environment is used, `CONDA_DEFAULT_ENV` will be set to a name, i.e., `base` or
72+
/// `root` which does not match the prefix, e.g. `/usr/local` instead of
73+
/// `/usr/local/conda/envs/<name>`.
74+
fn from_prefix_path(path: &Path) -> Self {
75+
// If we cannot read `CONDA_DEFAULT_ENV`, there's no way to know if the base environment
76+
let Ok(default_env) = env::var(EnvVars::CONDA_DEFAULT_ENV) else {
77+
return CondaEnvironmentKind::Child;
78+
};
79+
80+
// These are the expected names for the base environment
81+
if default_env != "base" && default_env != "root" {
82+
return CondaEnvironmentKind::Child;
83+
}
84+
85+
let Some(name) = path.file_name() else {
86+
return CondaEnvironmentKind::Child;
87+
};
88+
89+
if name.to_str().is_some_and(|name| name == default_env) {
90+
CondaEnvironmentKind::Base
91+
} else {
92+
CondaEnvironmentKind::Child
93+
}
94+
}
95+
}
96+
6097
/// Locate an active conda environment by inspecting environment variables.
6198
///
62-
/// Supports `CONDA_PREFIX`.
63-
pub(crate) fn conda_prefix_from_env() -> Option<PathBuf> {
64-
if let Some(dir) = env::var_os(EnvVars::CONDA_PREFIX).filter(|value| !value.is_empty()) {
65-
return Some(PathBuf::from(dir));
66-
}
99+
/// If `base` is true, the active environment must be the base environment or `None` is returned,
100+
/// and vice-versa.
101+
pub(crate) fn conda_environment_from_env(kind: CondaEnvironmentKind) -> Option<PathBuf> {
102+
let dir = env::var_os(EnvVars::CONDA_PREFIX).filter(|value| !value.is_empty())?;
103+
let path = PathBuf::from(dir);
67104

68-
None
105+
if kind != CondaEnvironmentKind::from_prefix_path(&path) {
106+
return None;
107+
};
108+
109+
Some(path)
69110
}
70111

71112
/// Locate a virtual environment by searching the file system.

crates/uv-static/src/env_vars.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,9 @@ impl EnvVars {
247247
/// Used to detect an activated Conda environment.
248248
pub const CONDA_PREFIX: &'static str = "CONDA_PREFIX";
249249

250+
/// Used to determine if an active Conda environment is the base environment or not.
251+
pub const CONDA_DEFAULT_ENV: &'static str = "CONDA_DEFAULT_ENV";
252+
250253
/// Disables prepending virtual environment name to the terminal prompt.
251254
pub const VIRTUAL_ENV_DISABLE_PROMPT: &'static str = "VIRTUAL_ENV_DISABLE_PROMPT";
252255

0 commit comments

Comments
 (0)