mypy icon indicating copy to clipboard operation
mypy copied to clipboard

False positive on re.compile as attrs converter

Open treuherz opened this issue 6 years ago • 4 comments

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

treuherz avatar Jul 03 '18 16:07 treuherz

Yes, this is a bug in mypy attrs plugin. We need to be more careful when a converter is generic.

ilevkivskyi avatar Jul 04 '18 09:07 ilevkivskyi

Just ran into this problem. Thanks for reporting!

ryansobol avatar Jun 02 '20 15:06 ryansobol

Ran into this as well. Same context.

Simplest workaround is defining a method like the following as a thin wrapper:

def compile_pattern(s: Union[str, bytes]) -> re.Pattern:
    return re.compile(s)


@attr.s
class Matcher:
    pattern: re.Pattern = attr.ib(converter=compile_pattern)

washogren avatar Aug 02 '21 18:08 washogren

Having the same issue, it seems to apply to TypeVar as well as generics:

import datetime as dt
from typing import TypeVar

import attr
import pandas as pd

DatetimeLike = TypeVar("DatetimeLike", dt.datetime, pd.DatetimeIndex)

def to_utc(t: DatetimeLike) -> DatetimeLike:
    ...  # this function is used on both types of objects


@attr.s(auto_attribs=True, frozen=True)
class Foo:
    bar: dt.datetime = attr.ib(converter=to_utc)


Foo(dt.datetime(...))

Running mypy on the above raises:

Argument 1 to "Foo" has incompatible type "datetime"; expected "DatetimeLike"

GiorgioBalestrieri avatar Dec 22 '22 16:12 GiorgioBalestrieri