从 python class 个变量中获取变量注释

Get variable annotations from python class variables

class User(Base)
    username: Annotated[str, 'exposed'] = "admin"
    password: Annotated[str, 'hidden']  = "admin"
    
print (username.__annotations__)

现在我想检查注释是否包含一些字符串 ex- 'exposed'。我怎样才能做到这一点?

您可以使用 typing.get_args(annotation) 获取类型参数的元组。例如:

class User:
    username: Annotated[str, 'exposed'] = "admin"
    password: Annotated[str, 'hidden'] = "admin"

>>> typing.get_args(User.__annotations__["username"])
(<class 'str'>, 'exposed')
>>> typing.get_args(User.__annotations__["username"])[1]
'exposed'