Default type for `Field.errors` of `tuple()` is immediately overwritten

Open Beginner friendly
#865 7 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
75/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Quiet
Tech stack
python
Domain
backend

Research direction

Start in src/wtforms/fields/core.py at the initialization around line 19 and reassignment around line 215, then inspect how Field.errors is used throughout validation. Reproduce the mypy example from the issue and verify that errors is consistently list-compatible without changing existing validation behavior.

Written by the indexing model from the issue text.

Description

The initial data type for Field.errors is set to a tuple:
https://github.com/pallets-eco/wtforms/blob/9cc223ad2fabeabd8d89021ea962b106d1502b6c/src/wtforms/fields/core.py#L19

which is reassigned to a list if there's any errors:
https://github.com/pallets-eco/wtforms/blob/9cc223ad2fabeabd8d89021ea962b106d1502b6c/src/wtforms/fields/core.py#L215

which causes type checkers like mypy to be sad when you use the field in your own code directly.

Actual Behavior

in repro.py:

import wtforms

class MyForm(wtforms.Form):
    name = wtforms.StringField()

    def validate(self, extra_validators=None, *args, **kwargs):
        super().validate(extra_validators, *args, **kwargs)

        if self.name.data == 'repro':
            # note the use of `append()`, unavailable on a tuple.
            self.name.errors.append('Name cannot be "repro"')
$ mypy --check-untyped-defs repro.py
repro.py:10: error: "Sequence[str]" has no attribute "append"  [attr-defined]
Found 1 error in 1 file (checked 1 source file)
Expected Behavior
$ mypy --check-untyped-defs repro.py
Success: no issues found in 1 source file
Environment
  • Python version: 3.12
  • wtforms version: 3.2.1
  • mypy version: 1.12.1

Yes, this specific example could be solved another way with validate_name, but that's not the point. The point is that the error's initial datatype is incorrect.
Everywhere it's used, it's treated as a list.

I'd be happy to send a PR changing to an empty list, but I didn't know if there was some other reason to have the data type as a tuple initially.

Dominant language
Python
Stars
1.6k
Forks
409
PR merge metrics
No merged PRs in 30d

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from pallets-eco/wtforms

All issues in pallets-eco/wtforms

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.