Created
October 28, 2021 13:28
-
-
Save aladinoster/5f85c7ccde88fde345ad52aebeee2d7a to your computer and use it in GitHub Desktop.
Python: Pool for smart instance management
This file contains hidden or 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
| """ Pool example for smart memory instantiation""" | |
| class Reusable: | |
| """Reusable class""" | |
| def test(self): | |
| """Test function""" | |
| print(f"Using object: {id(self)}") | |
| class ReusablePool: | |
| """Pool of Reusable classess""" | |
| def __init__(self, size): # pass items | |
| self.size = size | |
| self.free = [] | |
| self.in_use = [] | |
| for _ in range(size): | |
| self.free.append(Reusable()) | |
| def acquire(self): # you can acquire with __getitem__ or a special index | |
| """Acquire first item in the pool from free items""" | |
| if len(self.free) <= 0: | |
| raise BufferError("No available objects") | |
| acq_obj = self.free[0] | |
| self.free.remove(acq_obj) | |
| self.in_use.append(acq_obj) | |
| return acq_obj | |
| def release(self, obj: Reusable): | |
| """ Releases the item by appending it to the free items""" | |
| self.in_use.remove(obj) | |
| self.free.append(obj) | |
| print(f"Object back to pool: {id(obj)}") | |
| if __name__ == "__main__": | |
| pool = ReusablePool(2) | |
| r = pool.acquire() | |
| r.test() | |
| r2 = pool.acquire() | |
| r2.test() | |
| pool.release(r2) | |
| r3 = pool.acquire() | |
| r3.test() | |
| pool.release(r3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment