msgspec icon indicating copy to clipboard operation
msgspec copied to clipboard

Positional-only arguments

Open einarwar opened this issue 1 year ago • 0 comments
trafficstars

Description

Using msgspec.json.Decoder.decode() with a keyword arguments results in an error. Im guessing this has to do with the C-implementation. However, the error is only caught in runtime. Take the following example; Calling the function without a keyword works fine, calling it with does not.

import msgspec

class Foo(msgspec.Struct):
    a: int

decoder = msgspec.json.Decoder(Foo)

foo = Foo(a=1)
encoded = msgspec.json.encode(foo)

decoded = decoder.decode(encoded) # Works
decoded = decoder.decode(data=encoded) # Raises TypeError

I think this could be fixed by modifying the stub and adding a positional-only delimiter. Then one would get a warning if a type-checker like mypy or pyright is used.

By replacing: https://github.com/jcrist/msgspec/blob/2c37da090b2c5fcb2ecca9ae00274c67fabb85cf/msgspec/json.pyi#L76 with:

def decode(self, data: Union[bytes, str], /) -> T: ... 

This might also apply to other methods

einarwar avatar Jun 19 '24 13:06 einarwar