I am trying to create a function that enhances a type with another type. Below is a simple example…
def combine(name, A, B): # -> CombinationType[A, B]:
return type(name, (A, B), {})
class Hello:
def hello(self):
return "hello"
class Goodbye:
def goodbye(self):
return "goodbye"
both = combine("Both", Hello, Goodbye)
b = both()
b.hello() ■ Instance of 'Both' has no 'hello' member
b.goodbye() ■ Instance of 'Both' has no 'goodbye' member
mypy
doesn’t like the resulting Both
type, for obvious reasons (no return typehint on combine
).
Is there any way to represent something like this in python? You can assume the latest-and-greatest 3.12.x
or 3.13.x
My actual use case is a bit more involved, but conceptually the same: I want to take in a dataclass
type and create a new type that adds the ctypes.Structure
base and appropriate _fields_
values.
from ctypes import Structure, c_uint16
from dataclasses import dataclass
def structureify(datacls): # -> CombinationType[T, Structure]:
return type(datacls.__name__, (datacls, Structure), {"_fields_" = ...})
@structify
@dataclass
class Test:
test_member: c_uint16
And ideally I would like to be able to typehint/… on the resulting class (e.g. Test.from_buffer(...)
from Structure
, and Test.test_member
, …).
2