Advertisement
HasteBin0

Py3 print function

Jul 16th, 2020
1,392
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.30 KB | None | 0 0
  1. #!/user/bin/python3
  2. from typing import TextIO
  3. from sys import stdout, stderr
  4.  
  5.  
  6. _print_context: TextIO = stdout
  7.  
  8.  
  9. def print(*values, sep: str = ' ', end: str = '\n', file: TextIO = None, flush: bool = False) -> int:
  10.     out = _print_context if file is None else file
  11.     c_length = out.write(sep.join(map(str, values)) + end)
  12.     if flush:
  13.         out.flush()
  14.     return c_length
  15.  
  16.  
  17. class p_switcher:
  18.     _last_stream: TextIO
  19.     _this_stream: TextIO
  20.  
  21.     def __init__(self, out: TextIO):
  22.         self._last_stream = _print_context
  23.         self._this_stream = out
  24.  
  25.     def __enter__(self):
  26.         global _print_context
  27.         _print_context = self._this_stream
  28.  
  29.     def __exit__(self, exc_type, exc_val, exc_tb):
  30.         global _print_context
  31.         _print_context = self._last_stream
  32.  
  33.  
  34. if __name__ == '__main__':
  35.     print('Hello World!')
  36.     with p_switcher(stderr):
  37.         print('Hi', 5, flush = True)
  38.     print('This is', stdout, 'safe and sound.')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement