Advertisement
DeaD_EyE

random.choice Context Manager

Oct 24th, 2016
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.51 KB | None | 0 0
  1. import contextlib
  2. import random
  3.  
  4. # classical
  5. class Choice:
  6.  
  7.     def __init__(self, choices):
  8.         self.iterable = choices
  9.  
  10.     def __call__(self):
  11.         return random.choice(self.iterable)
  12.  
  13.     def __enter__(self):
  14.         return self()
  15.  
  16.     def __exit__(self, *args):
  17.         pass
  18.  
  19.  
  20. # with the decorator function
  21. @contextlib.contextmanager
  22. def choice(iterable):
  23.     yield random.choice(iterable)
  24.  
  25.  
  26. with choice([True, False]) as c:
  27.     print(c)
  28.  
  29. with Choice([True, False]) as c:
  30.     print(c)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement