Miscellaneous

  1. import sys
  2. import re
  3. from typing import Match, AnyStr, IO
  4.  
  5. # "typing.Match" describes regex matches from the re module
  6. x: Match[str] = re.match(r'[0-9]+', "15")
  7.  
  8. # Use IO[] for functions that should accept or return any
  9. # object that comes from an open() call (IO[] does not
  10. # distinguish between reading, writing or other modes)
  11. def get_sys_IO(mode: str = 'w') -> IO[str]:
  12. if mode == 'w':
  13. return sys.stdout
  14. elif mode == 'r':
  15. return sys.stdin
  16. else:
  17. return sys.stdout
  18.  
  19. # Forward references are useful if you want to reference a class before
  20. # it is defined
  21. def f(foo: A) -> int: # This will fail
  22. ...
  23.  
  24. class A:
  25. ...
  26.  
  27. # If you use the string literal 'A', it will pass as long as there is a
  28. # class of that name later on in the file
  29. def f(foo: 'A') -> int: # Ok
  30. ...