Last active
February 3, 2022 12:10
-
-
Save pprzetacznik/3c17d4168ca0d243a80d6fd50abe481c to your computer and use it in GitHub Desktop.
Context Managers in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pickle | |
class Board: | |
def __init__(self): | |
self.board = [['.']*3 for i in range(3)] | |
def mark(self, x, y, sign): | |
self.board[x][y] = sign | |
def serialize(self): | |
with open('board.pickle', 'wb') as f: | |
pickle.dump(self, f, pickle.HIGHEST_PROTOCOL) | |
@staticmethod | |
def deserialize(): | |
with open('board.pickle', 'rb') as f: | |
board = pickle.load(f) | |
return board | |
board = Board() | |
board.mark(0, 0, 'o') | |
board.serialize() | |
print(board.board) | |
board2 = Board.deserialize() | |
print(board2.board) | |
print(type(board2)) | |
class Contextmanager: | |
def __init__(self, generator): | |
self.generator = generator | |
def __call__(self, *args, **kwargs): | |
self.args, self.kwargs = args, kwargs | |
return self | |
def __enter__(self): | |
self.generator_instance = self.generator(*self.args, **self.kwargs) | |
return next(self.generator_instance) | |
def __exit__(self, *args): | |
try: | |
next(self.generator_instance) | |
except StopIteration: | |
print("StopIteration") | |
return self | |
# get_board = Contextmanager(get_board) | |
@Contextmanager | |
def get_board(): | |
print(f"Deserializing board") | |
board = Board.deserialize() | |
yield board | |
print(f"Serializing board") | |
with get_board() as board: | |
board.mark(0, 1, 'x') | |
print(board.board) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment