Page 1 of 1

Wie kann man überprüfen, ob ein Objekt ein Tipp ist.

Posted: 22 Aug 2025, 06:54
by Anonymous
Ich versuche Code zu schreiben, der Type -Hinweise validiert, und dazu muss ich herausfinden, welche Art von Objekt die Annotation ist. Betrachten Sie beispielsweise diesen Snippet, der dem Benutzer mitteilen soll, welche Art von Wert erwartet wird: < /p>

Code: Select all

import typing

typ = typing.Union[int, str]

if issubclass(typ, typing.Union):
print('value type should be one of', typ.__args__)
elif issubclass(typ, typing.Generic):
print('value type should be a structure of', typ.__args__[0])
else:
print('value type should be', typ)
< /code>
Dies sollte "Werttyp" drucken, sollte einer von (int, str) "sein, aber stattdessen löst es eine Ausnahme aus: < /p>
Traceback (most recent call last):
File "untitled.py", line 6, in 
if issubclass(typ, typing.Union):
File "C:\Python34\lib\site-packages\typing.py", line 829, in __subclasscheck__
raise TypeError("Unions cannot be used with issubclass().")
TypeError: Unions cannot be used with issubclass().
< /code>
isinstance
funktioniert auch nicht:

Code: Select all

>>> isinstance(typ, typing.Union)
Traceback (most recent call last):
File "", line 1, in 
File "C:\Python34\lib\site-packages\typing.py", line 826, in __instancecheck__
raise TypeError("Unions cannot be used with isinstance().")
TypeError: Unions cannot be used with isinstance().
Wie können Sie prüfen, ob Typ ein Typen ist. Aber wahrscheinlich wird es sich als Implementierungsdetail herausstellen und sich in zukünftigen Versionen ändern. Ich suche nach "den richtigen Weg" , um es zu tun.