msgspec icon indicating copy to clipboard operation
msgspec copied to clipboard

mypy plugin

Open jcrist opened this issue 5 years ago • 2 comments

Out of the box mypy will properly catch errors when using

  • msgspec.json.encode / msgspec.msgpack.encode
  • msgspec.json.decode / msgspec.msgpack.decode
  • msgspec.json.Decoder / msgspec.msgpack.Decoder
  • msgspec.json.Encoder / msgspec.msgpack.Encoder

This includes inferring the output type of the decode methods. It will also properly infer the type and presence/absence of attributes on msgspec.Struct objects. But it won't properly catch errors in the struct constructors.

import msgspec

class Point(msgspec.Struct):
    x: int
    y: int

p = Point(1, 2)
p.x + "string"   # mypy will catch this, since it knows `Point.x` is an int

p = Point("oops", "bad")  # this won't be caught by mypy

IIUC we'd need a mypy plugin to support this, similar to what pydantic does.

jcrist avatar Feb 23 '21 17:02 jcrist

I think this is what PEP 681 is intended to address. It isn't accepted, but an experimental version is available in pyright today.

ian-r-rose avatar Feb 12 '22 00:02 ian-r-rose

Yeah, we're already using that for pyright support (see https://github.com/jcrist/msgspec/blob/e25177e7ecb5f6593dbc38ddfdccdbc13e13daa8/msgspec/init.pyi#L4-L28). We'll still likely want a mypy plugin, since it doesn't look like mypy will support this any time soon.

jcrist avatar Feb 24 '22 14:02 jcrist