#🔒 [typing] Create new class dynamically from old class
14 messages · Page 1 of 1 (latest)
@karmic fractal
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
in typescript you would use generics + mapping, e.g.
type TypeA = {
field1: string
field2: boolean
}
type X<T> = {
[K in keyof T]: T[K] extends string ? number : T[K]
}
type TypeB = X<TypeA>
// ^? type TypeB = { field1: number; field2: bool…
ive tried asking Claude and ChatGPT but they both tap out pretty early when it comes to anything type-system related
Python's type system is very rudimentary. I don't think a Typescript equivalent of this is possible
well, python is not statically typed, and the existing type hinting is limited. so I wouldn't be surprised if such a thing isn't possible.
you'd probably just write a second class... or use a generic for those fields.
If you're using dataclasses, you can access dataclass_fields and just recreate it from that
There's also a variety of other options you can use to dynamically generate classes in python. type itself is a base fallback. You can also look into libraries like attrs which provide this as a major feature
However, I agree that it's unlikely you'll be able to type hint this
type hinting generated classes is a fiendish problem at the best of times, and given that it's relatively trivial to make nondeterministic most type checkers in python simply don't try
the best way I can think of would be just ```py
class TypeBase[T]:
field1: T
field2: bool
TypeA = TypeBase[str]
TypeB = TypeBase[int]
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.