python / python/typing

PEP 692 follow up: Unpacking compatibility with dataclass/others

Open
#1,495 11 comments 101 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: feature
Dominant language
Python
Stars
1.8k
Forks
302
Avg merge
23h
Merged PRs (30d)
8

Description

The Unpack addition has been great, however a lot of our code has an existing library of dataclasses instead of typed dictionaries. Here's a dummy example using one of the more common patterns that will suffer from this: factory methods.

from dataclasses import dataclass

from typing import Unpack


@dataclass
class Person:
    name: str
    age: int


# ERR: Expected TypeDict argument for Unpack
def person_factory(**kwargs: Unpack[Person]):
    return Person(**kwargs)


if __name__ == "__main__":
    steve = person_factory(name="Steve", age=42)

Right now, the "fix" for us would be to duplicate the dataclass as TypedDict, but code duplication is obviously not ideal. If there's another way, please let me know, otherwise I think a really valuable enhancement to the Unpack method would be to allow it to accept other objects, such as a dataclass or a pydantic BaseModel given the popularity of pydantic and FastAPI.

Antoher use case I can think of would be to be able to Unpack[function] or Unpack[class]. Common examples here would include matplotlib and plotly, where plotting functions often expose kwargs which just get passed to a child function. That child function has all the documentation and type hinting you'd need, but its unusable unless its copied into a TypeDict (I believe). For a concrete example, the top level maptlotlib plt.plot() function takes kwargs which are passed to the Line2D class

Contributor guide

No contributing guide indexed for this repository

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

Read the PEP 692 Unpack behavior and the factory-method example first. Compare the requested dataclass, pydantic BaseModel, and function/class cases, then define the supported scope and compatibility requirements. Done means the proposal has a decided, testable behavior rather than only duplicated TypedDict workarounds.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
developer-experience
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.