Skip to content

✨ Use Pydantic for parameter validation - #1831

Merged
tiangolo merged 167 commits into
fastapi:masterfrom
svlandeg:feat/pydantic
Nov 9, 2026
Merged

tiangolo merged 167 commits into
fastapi:masterfrom
svlandeg:feat/pydantic

Conversation

@svlandeg

@svlandeg svlandeg commented Jun 10, 2026 •

Copy link
Copy Markdown
Member

Meta: marked as a "feature", but definitely also "breaking" !

Description

Make Pydantic a required dependency and rely on it for parameter validation. Picked >=2.5.3 which is the current pin for github-actions.

Click's ParamType hierarchy is now replaced by a three-layer design:

  • TypeDescriptor objects store static facts about a parameter's type (in the new module coercion.py)
  • Pydantic TypeAdapter objects are defined in the new module adapters.py
  • RuntimeParam subclasses own coercion (also defined in coercion.py)

Further type-specific functionality is bundled in the new module param_types.py.

How to review this

  • Probably read all of the below first 👇
  • Note that _click/types.py and typer/_types.py are deleted
  • First look at typer/param_types.py, then typer/adapters.py, then typer/coercion.py
  • Look at the changes in typer/core.py
  • Check all other changes in typer/*.py
  • Check all changes in typer/_click/*.py
  • Check all changes in the test suite & documentation

Extended/improved functionality

  • More date time formats are now supported by default, instead of just the three [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]. Unix timestamps as seconds or milliseconds since the Unix epoch are now also supported.
  • Started moving towards a TyperParameter, not quite finished yet with some ugly imports from within _click but we'll deal with those in follow-up work

Tests with same behaviour on master

  • Added test_bool_convert_valid to ensure that the "bool" conversion has remained the same for all kinds of inputs.
  • Rewrote several tests to use Typer public API instead of internals
  • test_path_resolves, cf point 1) in the Fable review 👇

Breaking changes

(more or less in order of breakingness from most to least)

  • Removed support for click_type and open bounds through min_open and max_open. This greatly simplifies the code base while still providing an alternative by setting parser instead.
  • A list of choices is now shown as <list[Eggs|Bacon|Cheese]> (before there was no visual distinction between a single choice, or a list of them).
  • When not providing a default for DateTime, we just show "<datetime>". Before, it would show the (only) 3 options, but those are not exhaustive anymore. When the user provides actual formats, those are shown (as before).
  • Validation error messages have changed from Click's to Pydantic's phrasing. This mostly requires updating test suites and otherwise shouldn't impact users too badly.
  • Removed repr functionality of param.type. This wasn't really used except for the tests that were recently added in ➖ Vendor Click and streamline Typer's functionality and code base #1774.
  • A parameter typed as Any does NOT raise RuntimeError: Type not yet supported anymore, but instead just falls through and gets a generic TypeAdapter(annotation)

Note that as before, nothing in the module typer/_click (a remnant of the recent vendoring) should be used directly by users and all of it is subject to change in the near future. Any changes in those modules are not considered to be "breaking".

Bug fixes (also breaking bwd compat)

  • def main(age: int = typer.Option(15.3)) will now throw a validation error by Pydantic instead of int(15.3) converting it to 15. I consider this a bug fix instead of a regression, and have added a test test_int_rejects_float_default for it.
  • Tuples with types that aren't allowed to be None (e.g. tuple[str, int, bool]), will fail validation as soon as one of those elements is None. Our documented example of setting that tuple's default to (None, None, None) is not valid anymore, it should be set to None instead. cf. change to ‎docs_src/multiple_values/options_with_multiple_values/tutorial001_an_py310.py.
  • Types are now inferred from the default if the parameter is untyped. Fixes Default value of `False` cast to `'False'` and is thus True #942, cf. new test test_default_infers_param_type.
  • With Rich disabled, types were always shown for options, but for arguments only when they were "informative" like a tuple or datetime. This PR makes everything internally consistent, and similar to how it looks with Rich enabled, by always showing the types also for arguments.

Decision points

  • _parse_cli_bool was created to ensure we still parse "" as False and to strip whitespace from something like " True ". This is just to mimic old Click behaviour. If we don't do this preprocessing (cleaner code base), the empty string and the non-stripped strings won't pass Pydantic validation and it would be slightly breaking.
  • How to display the datetime type if no formats are provided by the user (cf ☝️ "Breaking changes")
  • Should we allow an int or float as datetime input, to present Unix timestamps as seconds or milliseconds since the Unix epoch? Cf also Fable's concern in point 4 of its review below 👇
  • Should we try to do less with Pydantic to avoid runtime increase? (cf point 7 in Fable's review)

AI Disclaimer

Cursor was used as a micro-managed junior. Every edit was reviewed & understood by me.

TODO

  • Mention Pydantic dependency in the docs
  • Update the tutorial, focus on (changed) error messages
  • Fix coverage
  • Merge in the fix from 🏷️ Make Parameter.name typed as str instead of str | None #1878
  • I added tests for the change.
  • Coverage stays at 100%.
  • Metavar printing that came up in this PR has already been fixed in tests & documentation in 💥 Update metavar printing #1863.
  • Self review with Fable, after which: "This v2 is a substantial improvement — most of what we discussed landed, and several of the fixes are better than what I suggested." 😎

Follow-up work

  • Continue cleaning up code in typer/_click
  • Expand code/docs/tests to support many more data types (should be straightforward?!)
  • Test/document Pydantic models for re-usable CLI Options

@svlandeg svlandeg added the feature New feature, enhancement or request label Jun 10, 2026
("No", False),
],
)
def test_bool_convert_valid(cli_value: str, expected: bool) -> None:

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test currently mimics master behaviour 100%.

@svlandeg svlandeg self-assigned this Jun 10, 2026
@github-actions

github-actions Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

📝 Docs preview

Last commit 93bfa93 at: https://e189570c.typertiangolo.pages.dev

Modified Pages

@svlandeg

svlandeg commented Oct 26, 2026 •

Copy link
Copy Markdown
Member Author

@tiangolo:

I updated this branch with master's latest, have a quick look at 1b1ceb7 which changes a control char test case to mimic Pydantic's error formatting, I think this is fine?

And then:

I would like to make anything new "private" by default.

Modules renamed:

  • adapters.py → _adapters.py
  • coercion.py → _coercion.py
  • display.py → _display.py
  • param_types.py → _param_types.py

New symbols in existing modules:

  • TyperParameter → _TyperParameter (in core.py)
  • get_param → _get_param (in main.py)
  • get_option_flag_name → _get_option_flag_name (in main.py)
  • get_params_ctx_param_name_from_function → _get_params_name_from_function (in main.py)
  • get_number_range_help_str → _get_number_range_help_str (TyperArgument function in core.py)
  • rich_display_name → _rich_display_name (TyperArgument function in core.py)
  • usage_display_name → _usage_display_name (TyperArgument function in core.py)

@svlandeg svlandeg removed their assignment Oct 26, 2026
@github-actions github-actions Bot added the conflicts Automatically generated when a PR has a merge conflict label Nov 4, 2026
@github-actions

This comment was marked as resolved.

@Viicos

Viicos commented Nov 8, 2026

Copy link
Copy Markdown

On pydantic's startup time, I'd also suggest setting PYDANTIC_DISABLE_PLUGINS=1, as Pydantic uses entry points to load plugins (which can trigger other imports too such as our logfire SDK) and it is questionable whether any plugins are necessary for validation of CLI invocation.

# Conflicts:
#	typer/_click/core.py
#	typer/main.py
@github-actions github-actions Bot removed the conflicts Automatically generated when a PR has a merge conflict label Nov 9, 2026
@svlandeg

svlandeg commented Nov 9, 2026 •

Copy link
Copy Markdown
Member Author

On pydantic's startup time, I'd also suggest setting PYDANTIC_DISABLE_PLUGINS=1, as Pydantic uses entry points to load plugins (which can trigger other imports too such as our logfire SDK) and it is questionable whether any plugins are necessary for validation of CLI invocation.

Thanks for the note @Viicos! 🙏

I've created a context manager disabled_pydantic_plugins() which sets PYDANTIC_DISABLE_PLUGINS to 1 and afterwards restores the original value. It's called in try_build_adapter and in coerce_cli_path.

If I understand correctly, this env var works since Pydantic 2.7.0 and our lower pin in 2.5.3. That means that for older Pydantic versions, this is a no-op. I think that's fine and no reason to raise the floor.

7976dda

@tiangolo tiangolo left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Amazing, I'm so excited about this! 🚀 🤩

@tiangolo
tiangolo merged commit 7ca7c48 into fastapi:master Nov 9, 2026
24 checks passed
@relativityspace-jsmith

Copy link
Copy Markdown

I'm sorry but this change should have triggered a 1.0 release. It should not have been a 0.x release. First I want to say, I love Pydantic and am glad to see it being used for this type of purpose. However, this change (in particular the removal of the vendored click and the removal of click_type) is going to trigger a massive amount of breakages and churn in packages that use typer. It's only been 3 hours since this was released and it already broke a CI build at my company!

Overall I have been extremely disappointed with the breaking changes to Typer that have occurred over the last year. First there was the vendoring of click (which caused breakages in anything that used click_type and assumed Typer would pull in a click dependency). Now there's this change which completely removed support for custom click_types. Both of these were done with no advance warning to users, such as publishing a change roadmap in advance and/or issuing a DeprecationWarning for users of click_type. And while this is an advanced feature, it's by no means an esoteric one -- I have used it in several apps over the years to get non-backwards Enum support. In any serious library, including a feature like this in a public release is an implicit contract that the feature will be supported in future releases, until and unless it is properly (over a long time or via a major release) deprecated and removed, and you guys are just not doing this at all.

Yes, I know Typer is still ZeroVer and still claims to be in "beta" status, but it must have hundreds of thousands of users now -- you cannot seriously tell me that it's appropriate to break a significant fraction of those users' code with no advance warning whenever you feel like it. At this point I am forced to conclude that Typer is still a "sandbox" project and simply not appropriate for any sort of serious work, because breaking changes just happen all the time with no advance warning (without even being listed in the changelog!). Since the previous breakage I have already been migrating all my apps to cyclopts, and will have to accelerate this now to prevent future issues. While it does have some of its own idiosyncrasies, this library has shown a much stronger commitment to following a reasonable versioning system and signaling any breaking changes well in advance. As for Typer, I would really, strongly recommend that you guys publish a roadmap to get to the 1.0 version and declare any breaking changes much further in advance in the future.

alyssadai added a commit to neurobagel/bagel-cli that referenced this pull request Nov 9, 2026
@svlandeg
svlandeg deleted the feat/pydantic branch November 9, 2026 23:02
alyssadai added a commit to neurobagel/bagel-cli that referenced this pull request Nov 10, 2026
…rrors, handle similar failures consistently (#750)

* raise BagelValidationError instead of logging + exiting in phenotypic input validations

* log independent pheno input validation errors together and refactor age transform error raising

* raise BagelFileError instead of calling log_error for input file parsing errors

* handle logging and exiting for phenotypic file parsing errors

* raise BagelValidationError and BagelResourceError in BIDS steps

* handle error with vocab fetching in main command

* refactor BIDS validations

* create PipelineCatalog class to allow lazy-loading of remote catalog on first access

* handle subjects missing from phenotypic data in main command logic

* remove leftover utility for checking pipeline catalog availability

* standardize handling of resource fetching

* rename validate_dataset_description to convey that it returns a validated object

* raise BagelValidationError instead of logging + exiting for pipeline-version validation

* update assertions and mocks for requested resources in integration tests

* update error assertions in tests

* test pheno file parsing errors returned together

* test app exits when BIDS vocab fetching fails

* test harmonize-pheno errors gracefully for age transformation failure

* add placeholder dataset description to test of input file parsing errors

* separate logging and exiting globally

* catch age transformation error more precisely

* temporarily pin typer to avoid removed support for click_type from 0.29.0
- fastapi/typer#1831

* test bids2tsv exits gracefully for failed BIDS vocab fetching

* test informative error when BIDS subjects don't match pheno subjects
surchs pushed a commit to neurobagel/testplace that referenced this pull request Nov 10, 2026
…rors, handle similar failures consistently (neurobagel/bagel-cli#750)

* raise BagelValidationError instead of logging + exiting in phenotypic input validations

* log independent pheno input validation errors together and refactor age transform error raising

* raise BagelFileError instead of calling log_error for input file parsing errors

* handle logging and exiting for phenotypic file parsing errors

* raise BagelValidationError and BagelResourceError in BIDS steps

* handle error with vocab fetching in main command

* refactor BIDS validations

* create PipelineCatalog class to allow lazy-loading of remote catalog on first access

* handle subjects missing from phenotypic data in main command logic

* remove leftover utility for checking pipeline catalog availability

* standardize handling of resource fetching

* rename validate_dataset_description to convey that it returns a validated object

* raise BagelValidationError instead of logging + exiting for pipeline-version validation

* update assertions and mocks for requested resources in integration tests

* update error assertions in tests

* test pheno file parsing errors returned together

* test app exits when BIDS vocab fetching fails

* test harmonize-pheno errors gracefully for age transformation failure

* add placeholder dataset description to test of input file parsing errors

* separate logging and exiting globally

* catch age transformation error more precisely

* temporarily pin typer to avoid removed support for click_type from 0.29.0
- fastapi/typer#1831

* test bids2tsv exits gracefully for failed BIDS vocab fetching

* test informative error when BIDS subjects don't match pheno subjects
@tiangolo

Copy link
Copy Markdown
Member

@relativityspace-jsmith I understand the frustration of having an upgrade break your CI. Could you open a discussion with a minimal example of your click_type implementation and the behavior you need to preserve? That would help us assess migration options and identify any gaps.

@relativityspace-jsmith

relativityspace-jsmith commented Nov 10, 2026 •

Copy link
Copy Markdown

Hi, thank you for following up. The actual functionality that I needed (the ability to use an enum's names to set the values for an option) is well described by #1572 . I was using click_type as a way to work around the lack of this feature (see the comments on that discussion for the workaround I was using).

But most of my concerns here aren't related to this specific issue or to click_type. What I am very concerned by is the willingness with which you guys made a significant breaking change without issuing any real notice to users (e.g. an advance deprecation warning or roadmap or major version bump). And this is the second time that typer has done this to me within the last year!

@tiangolo

tiangolo commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

Thanks for clarifying. The migration was informed by our developer survey, which showed strong interest in Pydantic and very low use of Click-specific features. I understand the disruption, and the release notes could have been clearer about the removal of click_type.

Edit: I also edited the release notes with the main relevant changes I could fine (with the help of Codex / Astra).

@svlandeg

Copy link
Copy Markdown
Member Author

All, thanks for the discussion here! I suggest to have further follow-up discussions in the actual discussion forum, which will make it easier to track them. Thanks 🙏

@fastapi fastapi locked and limited conversation to collaborators Nov 11, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

feature New feature, enhancement or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants