python / python/typing

Merging/Modifying Types

Open
#1,490 3 comments 1 reaction 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

I have a decorator that modifies a class at runtime, kind of like a dataclass:

@modify
class Something:
    ...

Let's say modify adds foo onto Something, so after calling modify you could use it like so:

@modify
class Something
    ...

bar = Something.foo()

dataclass_transform doesn't support this kind of behavior at all. So, how would an API like this work?

I don't see why it would be difficult to implement some sort of Merge type, that takes in a type and "applies"" a Protocol to it. For the above example, it would work like this:

T = TypeVar("T")

class FooProtocol(Protocol):
    @classmethod
    def foo() -> None:
        ...

def modify(tp: type[T]) -> Merge[T, FooProtocol]:
    tp.foo = ...  # type: ignore
    return tp

@modify
class Something:
    ...

bar = Something.foo()

In the above example, ideally it would just sort of mark that the T is now compatible with FooProtocol, but a type: ignore is used inside of modify because it would probably be a mess to try and come up with some sort of API for actually converting a T to Merge[T, ...].

TL;DR A type that marks another type as being compatible with a protocol could be handy for making dataclass-like decorators.

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

Start by reviewing the proposed Merge type and the dataclass_transform limitation described in the issue. Determine whether the typing specification has an appropriate place for this behavior and what compatibility and decorator semantics would need to be defined; the issue provides no files, tests, or concrete implementation entry point.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.