Home > OS >  Get variable annotations from python class variables
Get variable annotations from python class variables

Time:12-17

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

Now I would like to check if the annotation contains some string ex- 'exposed'. How can I achieve this?

CodePudding user response:

You can use typing.get_args(annotation) to get a tuple of the arguments to a type. For instance:

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'
  • Related