python / python/mypy

False positive on re.compile as attrs converter

Open
#5,313 4 comments 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug false-positive priority-1-normal topic-attrs topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

I've found what I think is a bug in mypy's attrs support.

# test.py
import re
import attr

@attr.s
class Test:
    foo = attr.ib(converter=re.compile)

test = Test("foo")
$ mypy test.py
test.py:8: error: Argument 1 to "Test" has incompatible type "str"; expected "Union[AnyStr, Pattern[AnyStr]]"

Unless I've completely misunderstood what AnyStr is for, I don't think that signature should throw on receiving a string.

I can't quite figure out if attrs or mypy is at fault here, but I can't get the same error to appear on re.compile when it's not being applied as a converter by attrs. Apologies if I've missed an obvious issue here.

Python v3.6.5
Mypy v0.610
Attrs v18.1.0

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.

Research direction

Start by reproducing the report with the shown test.py and compare mypy's handling of re.compile alone with its handling as an attrs converter. Trace the attrs converter type inference and the resulting constructor argument check. Done means Test("foo") is accepted without weakening valid converter typing.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.