Guest User

Untitled

a guest
Jun 9th, 2022
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. import typing
  2.  
  3.  
  4. def construct_query_class(cls):
  5.     annotations = {key: typing.Optional[value] for key, value in cls.__annotations__.items()}
  6.     return type(cls.__name__ + 'Query', (), {'__annotations__': annotations})
  7.  
  8.  
  9. class SomeResource:
  10.     id: int
  11.     name: str
  12.  
  13.  
  14. SomeResourceQuery = construct_query_class(SomeResource)
  15.  
  16. if __name__ == "__main__":
  17.     test0: SomeResource = SomeResource()
  18.     test0.id = 1
  19.     test0.name = "stian"
  20.  
  21.     test: SomeResourceQuery = SomeResourceQuery()
  22.     test.id = 1  # Pycharm isn't helping with autocompletion here
  23.  
  24.     # Also, mypy has this to say about this file:
  25.     #   testing.py:21: error: Variable "testing.SomeResourceQuery" is not valid as a type
  26.     #   testing.py:21: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
  27.     #   testing.py:22: error: SomeResourceQuery? has no attribute "id"
  28.     #   Found 2 errors in 1 file (checked 1 source file)
  29.  
Add Comment
Please, Sign In to add comment