I'm trying to write a function that introspects the types of fields in a dataclass (this is to automatically generate SQL table creation statements). However, I have a problem when dealing with generic types. In particular, if I have a field with the type `Optional[int]`, I want to create a SQL column of type `INTEGER`, but without a `NOT NULL` constraint (so nulls are allowed). But I can't work out how to introspect the type of the field, to determine that it's based on `int`.
```
from dataclasses import dataclass, fields
from typing import Optional
@dataclass
class Example:
mandatory: int
optional: Optional[int]
for f in fields(Example):
print(f.type)
```
This displays:
```
<class 'int'>
typing.Optional[int]
```
But from `f.type`, I can't find any way to confirm it's an optional type (issubclass gives "TypeError: Subscripted generics cannot be used with class and instance checks") and I can't recover the "underlying" integer type.
I understand that introspecting types at runtime is not the key use case for annotations, but with the availability of dataclasses in the standard library, it seems like this sort of usage is only going to become more common, as it's an extremely obvious way to handle this type of requirement, and the alternative, using field metadata, is very verbose:
```
>>> @dataclass
... class Example:
... mandatory: int = field(metadata={"sql_type": "INTEGER"})
... optional: Optional[int] = field(metadata={"sql_type": "INTEGER", "allow_null": True})
```
Is there a reasonable way to do this? Or is it something that's likely to be added in the foreseeable future?
_______________________________________________
Typing-sig mailing list -- typing-sig@python.org
To unsubscribe send an email to typing-sig-leave@python.org
https://mail.python.org/mailman3/lists/typing-sig.python.org/
Member address: tinchester@gmail.com