Advertisement
Guest User

Untitled

a guest
Nov 27th, 2020
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | None | 0 0
  1. from time import sleep
  2. from typing import Move, List
  3. from io import FileIO, BytesIO
  4. from dataclasses import dataclass
  5. from threading import Thread
  6.  
  7.  
  8. def read_and_close_file(file: Move[FileIO]):
  9.     """ File will be closed, so we can not use after """
  10.     file.read()
  11.     file.close()
  12.  
  13.  
  14. @dataclass
  15. class Model:
  16.     x: List[int]
  17.  
  18.  
  19. def make_list_from_model(model: Move[Model]) -> List[int]:
  20.     """ This is not a pure function, which is bad,
  21.    but if we move model here and won't use it after, then it's kinda pure """
  22.     model.x.append(1)  # x is big and we don't want to copy it, instead we just push another element
  23.     return model.x
  24.  
  25.  
  26. def run_thread_unsafe_process(writer: Move[BytesIO]) -> Thread:
  27.     thread = Thread(target=thread_unsafe_process, args=(writer,))
  28.     thread.start()
  29.     return thread
  30.  
  31.  
  32. def thread_unsafe_process(writer: BytesIO):
  33.     while True:
  34.         sleep(1)
  35.         writer.write(b'Hello!')
  36.  
  37.  
  38. file = open('move.py')
  39. read_and_close_file(file)
  40. file.read()  # Mistake, file is already closed, static analyzer cah check that
  41.  
  42. model = Model([1, 2, 3])
  43. y = make_list_from_model(model)
  44. print(model.x)  # Using of corrupted value, it might be unexpected for caller and cause some mistakes
  45.  
  46. writer = open('buffer.tmp', 'wb')
  47. run_thread_unsafe_process(writer)
  48. writer.write(b'world')  # mistake, can lead to data-race (in this case, two messages, "hello" and "world", might mix up)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement