Advertisement
treyhunner

smoosh.py

Mar 17th, 2018
585
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.80 KB | None | 0 0
  1. """
  2. smoosh module allowing for smoosh levels specified by number of o's
  3.  
  4. >>> import smoosh
  5. >>> list(smoosh.smoosh([1,[2,[3,[4]]]]))
  6. [1, 2, [3, [4]]]
  7. >>> list(smoosh.smooosh([1,[2,[3,[4]]]]))
  8. [1, 2, 3, [4]]
  9. >>> list(smoosh.smoooosh([1,[2,[3,[4]]]]))
  10. [1, 2, 3, 4]
  11.  
  12. """
  13. from collections.abc import Iterable
  14. from functools import partial
  15. import re
  16.  
  17.  
  18. def _flatten(iterable, depth):
  19.     for item in iterable:
  20.         if not isinstance(item, Iterable) or depth == 0:
  21.             yield item
  22.         else:
  23.             yield from _flatten(item, depth-1)
  24.  
  25.  
  26. def __getattr__(name):
  27.     if re.search(r'^smoo+sh$', name):
  28.         return partial(_flatten, depth=name.count('o')-1)
  29.     raise AttributeError(f"module {__name__} has no attribute {name}")
  30.  
  31.  
  32. __all__ = [f'smoo{"o" * i}sh' for i in range(20)]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement