0

In set theory you can subtract set B from set A to derive a new set consisting of members that are in A but not in B.

A = {x,y,z}
B = {z}
C = A - B = {x,y}

I want to achieve this in Python by subtracting two TypedDicts to derive a new type annotation

class A(TypedDict):
    x: int
    y: int
    z: int

class B(TypedDict):
    z: int

C = type(A - B) # <- fake code, what I'm looking for

def f() -> C:
    return {'x':0,'y':0}

Languages like TypeScript seem to support this operation. Does Python?

Michael Moreno
  • 947
  • 1
  • 7
  • 24
  • 4
    I'm pretty sure Python's type system does not support this... It doesn't surprise me that TypeScript does, since TypeScript uses structural typing as the main paradigm, in Python, the main paradigm is nominal typing but there is some basic support for some structural typing (e.g. `typing.Protocol` along with `typing.TypedDict`) but hardly with all the bells and whistles that TypeScript has – juanpa.arrivillaga Feb 01 '23 at 22:26
  • `TypedDict`s might be constrained enough to make `C = A - B` a feasible feature request, though you'd have to demonstrate that the need for such syntax was great enough to warrant the complexity of implementing it. Also: what if `B.z` had a type other than `int`; would you want it `A.z` to be included in `C` or not? – chepner Feb 01 '23 at 22:39
  • 1
    Similar to @chepner's question: what if the classes have methods defined as well? Also, this sounds like a possible XY Problem - what are you trying to achieve that made you want to do this in the first place? You could construct a new class in a function that takes classes as arguments, possibly even using the actual set type to perform that logic? – Grismar Feb 01 '23 at 22:58
  • I'd go the other way around and explicitly declare `C` as a class, and then use [inheritance](https://peps.python.org/pep-0589/#inheritance) to implement `A`. – Itai Steinherz Feb 02 '23 at 09:16

0 Answers0