Skip to content

Commit 06e8700

Browse files
committed
Incorporate alias changes
1 parent fa426e5 commit 06e8700

File tree

2 files changed

+41
-26
lines changed

2 files changed

+41
-26
lines changed

python/pydantic_core/core_schema.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3549,7 +3549,8 @@ def arguments_v3_parameter(
35493549
class ArgumentsV3Schema(TypedDict, total=False):
35503550
type: Required[Literal['arguments-v3']]
35513551
arguments_schema: Required[list[ArgumentsV3Parameter]]
3552-
populate_by_name: bool
3552+
validate_by_name: bool
3553+
validate_by_alias: bool
35533554
var_args_schema: CoreSchema
35543555
var_kwargs_mode: VarKwargsMode
35553556
var_kwargs_schema: CoreSchema
@@ -3561,7 +3562,8 @@ class ArgumentsV3Schema(TypedDict, total=False):
35613562
def arguments_v3_schema(
35623563
arguments: list[ArgumentsV3Parameter],
35633564
*,
3564-
populate_by_name: bool | None = None,
3565+
validate_by_name: bool | None = None,
3566+
validate_by_alias: bool | None = None,
35653567
ref: str | None = None,
35663568
metadata: dict[str, Any] | None = None,
35673569
serialization: SerSchema | None = None,
@@ -3584,16 +3586,18 @@ def arguments_v3_schema(
35843586
```
35853587
35863588
Args:
3587-
arguments: The arguments to use for the arguments schema
3588-
populate_by_name: Whether to populate by name
3589-
ref: optional unique identifier of the schema, used to reference the schema in other places
3590-
metadata: Any other information you want to include with the schema, not used by pydantic-core
3591-
serialization: Custom serialization schema
3589+
arguments: The arguments to use for the arguments schema.
3590+
validate_by_name: Whether to populate by the parameter names, defaults to `False`.
3591+
validate_by_alias: Whether to populate by the parameter aliases, defaults to `True`.
3592+
ref: optional unique identifier of the schema, used to reference the schema in other places.
3593+
metadata: Any other information you want to include with the schema, not used by pydantic-core.
3594+
serialization: Custom serialization schema.
35923595
"""
35933596
return _dict_not_none(
35943597
type='arguments-v2',
35953598
arguments_schema=arguments,
3596-
populate_by_name=populate_by_name,
3599+
validate_by_name=validate_by_name,
3600+
validate_by_alias=validate_by_alias,
35973601
ref=ref,
35983602
metadata=metadata,
35993603
serialization=serialization,

src/validators/arguments_v3.rs

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use crate::errors::{ErrorTypeDefaults, ValError, ValLineError, ValResult};
1313
use crate::input::{
1414
Arguments, BorrowInput, Input, KeywordArgs, PositionalArgs, ValidatedDict, ValidatedTuple, ValidationMatch,
1515
};
16-
use crate::lookup_key::LookupKey;
16+
use crate::lookup_key::LookupKeyCollection;
1717
use crate::tools::SchemaDict;
1818

1919
use super::validation_state::ValidationState;
@@ -49,7 +49,7 @@ impl FromStr for ParameterMode {
4949
struct Parameter {
5050
name: String,
5151
mode: ParameterMode,
52-
lookup_key: LookupKey,
52+
lookup_key_collection: LookupKeyCollection,
5353
validator: CombinedValidator,
5454
}
5555

@@ -70,6 +70,8 @@ pub struct ArgumentsV3Validator {
7070
positional_params_count: usize,
7171
loc_by_alias: bool,
7272
extra: ExtraBehavior,
73+
validate_by_alias: Option<bool>,
74+
validate_by_name: Option<bool>,
7375
}
7476

7577
impl BuildValidator for ArgumentsV3Validator {
@@ -82,8 +84,6 @@ impl BuildValidator for ArgumentsV3Validator {
8284
) -> PyResult<CombinedValidator> {
8385
let py = schema.py();
8486

85-
let populate_by_name = schema_or_config_same(schema, config, intern!(py, "populate_by_name"))?.unwrap_or(false);
86-
8787
let arguments_schema: Bound<'_, PyList> = schema.get_as_req(intern!(py, "arguments_schema"))?;
8888
let mut parameters: Vec<Parameter> = Vec::with_capacity(arguments_schema.len());
8989

@@ -113,14 +113,6 @@ impl BuildValidator for ArgumentsV3Validator {
113113
had_keyword_only = true;
114114
}
115115

116-
let lookup_key = match arg.get_item(intern!(py, "alias"))? {
117-
Some(alias) => {
118-
let alt_alias = if populate_by_name { Some(name.as_str()) } else { None };
119-
LookupKey::from_py(py, &alias, alt_alias)?
120-
}
121-
None => LookupKey::from_string(py, &name),
122-
};
123-
124116
let schema = arg.get_as_req(intern!(py, "schema"))?;
125117

126118
let validator = match build_validator(&schema, config, definitions) {
@@ -143,10 +135,14 @@ impl BuildValidator for ArgumentsV3Validator {
143135
} else if has_default {
144136
had_default_arg = true;
145137
}
138+
139+
let validation_alias = arg.get_item(intern!(py, "alias"))?;
140+
let lookup_key_collection = LookupKeyCollection::new(py, validation_alias, name.as_str())?;
141+
146142
parameters.push(Parameter {
147143
name,
148144
mode,
149-
lookup_key,
145+
lookup_key_collection,
150146
validator,
151147
});
152148
}
@@ -166,6 +162,8 @@ impl BuildValidator for ArgumentsV3Validator {
166162
positional_params_count,
167163
loc_by_alias: config.get_as(intern!(py, "loc_by_alias"))?.unwrap_or(true),
168164
extra: ExtraBehavior::from_schema_or_config(py, schema, config, ExtraBehavior::Forbid)?,
165+
validate_by_alias: schema_or_config_same(schema, config, intern!(py, "validate_by_alias"))?,
166+
validate_by_name: schema_or_config_same(schema, config, intern!(py, "validate_by_name"))?,
169167
}
170168
.into())
171169
}
@@ -194,9 +192,15 @@ impl ArgumentsV3Validator {
194192
let output_kwargs = PyDict::new(py);
195193
let mut errors: Vec<ValLineError> = Vec::new();
196194

195+
let validate_by_alias = state.validate_by_alias_or(self.validate_by_alias);
196+
let validate_by_name = state.validate_by_name_or(self.validate_by_name);
197+
197198
for parameter in self.parameters.iter() {
199+
let lookup_key = parameter
200+
.lookup_key_collection
201+
.select(validate_by_alias, validate_by_name)?;
198202
// A value is present in the mapping:
199-
if let Some((lookup_path, dict_value)) = mapping.get_item(&parameter.lookup_key)? {
203+
if let Some((lookup_path, dict_value)) = mapping.get_item(&lookup_key)? {
200204
match parameter.mode {
201205
ParameterMode::PositionalOnly | ParameterMode::PositionalOrKeyword => {
202206
match parameter.validator.validate(py, dict_value.borrow_input(), state) {
@@ -327,7 +331,7 @@ impl ArgumentsV3Validator {
327331
_ => unreachable!(),
328332
};
329333

330-
errors.push(parameter.lookup_key.error(
334+
errors.push(lookup_key.error(
331335
error_type,
332336
original_input,
333337
self.loc_by_alias,
@@ -367,8 +371,15 @@ impl ArgumentsV3Validator {
367371
let mut errors: Vec<ValLineError> = Vec::new();
368372
let mut used_kwargs: AHashSet<&str> = AHashSet::with_capacity(self.parameters.len());
369373

374+
let validate_by_alias = state.validate_by_alias_or(self.validate_by_alias);
375+
let validate_by_name = state.validate_by_name_or(self.validate_by_name);
376+
370377
// go through non variadic arguments, getting the value from args or kwargs and validating it
371378
for (index, parameter) in self.parameters.iter().filter(|p| !p.is_variadic()).enumerate() {
379+
let lookup_key = parameter
380+
.lookup_key_collection
381+
.select(validate_by_alias, validate_by_name)?;
382+
372383
let mut pos_value = None;
373384
if let Some(args) = args_kwargs.args() {
374385
if matches!(
@@ -385,7 +396,7 @@ impl ArgumentsV3Validator {
385396
parameter.mode,
386397
ParameterMode::PositionalOrKeyword | ParameterMode::KeywordOnly
387398
) {
388-
if let Some((lookup_path, value)) = kwargs.get_item(&parameter.lookup_key)? {
399+
if let Some((lookup_path, value)) = kwargs.get_item(&lookup_key)? {
389400
used_kwargs.insert(lookup_path.first_key());
390401
kw_value = Some((lookup_path, value));
391402
}
@@ -446,15 +457,15 @@ impl ArgumentsV3Validator {
446457
));
447458
}
448459
ParameterMode::PositionalOrKeyword => {
449-
errors.push(parameter.lookup_key.error(
460+
errors.push(lookup_key.error(
450461
ErrorTypeDefaults::MissingArgument,
451462
original_input,
452463
self.loc_by_alias,
453464
&parameter.name,
454465
));
455466
}
456467
ParameterMode::KeywordOnly => {
457-
errors.push(parameter.lookup_key.error(
468+
errors.push(lookup_key.error(
458469
ErrorTypeDefaults::MissingKeywordOnlyArgument,
459470
original_input,
460471
self.loc_by_alias,

0 commit comments

Comments
 (0)