msgspec / msgspec/msgspec

support decoding to `collections.Counter`

Open
#861 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
4.1k
Forks
193
Avg merge
3d 20h
Merged PRs (30d)
15

Description

Description

This is something pydantic supports, but not msgspec:

from collections import Counter

c: Counter[str] = Counter()

c["abc"] += 3
c["xyz"] += 1


def pyd() -> None:
    import pydantic
    CounterStr = pydantic.TypeAdapter(Counter[str])
    c_serialized = CounterStr.dump_json(c)
    print(c_serialized)
    c_deserialized = CounterStr.validate_json(c_serialized)
    print(c_deserialized)


def msg() -> None:
    import msgspec
    CounterStr = msgspec.json.Decoder(Counter[str])
    c_serialized = msgspec.json.encode(c)
    print(c_serialized)
    c_deserialized = CounterStr.decode(c_serialized)
    print(c_deserialized)


pyd()
msg()

output:

b'{"abc":3,"xyz":1}'
Counter({'abc': 3, 'xyz': 1})
b'{"abc":3,"xyz":1}'
Traceback (most recent call last):
...
msgspec.ValidationError: Expected `Counter`, got `dict`

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 with the msgspec.json.Decoder(Counter[str]) example and compare its behavior with pydantic's Counter handling. Add support so decoding the encoded mapping returns a Counter with the same counts, and cover the behavior with a regression test for the shown example.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.