Mapytex/pymath/calculus/decorators.py

45 lines
1.1 KiB
Python
Raw Normal View History

#!/usr/bin/env python
# encoding: utf-8
from functools import wraps
def no_repetition(equals=lambda x,y: x == y):
""" Remove yield values which has already been yield
:param fun: a generator
:returns: same generator with no repetitions
>>> norep = no_repetition()
>>> def str_gene(string):
... for i in string:
... yield i
>>> norep_str_gene = norep(str_gene)
>>> [i for i in norep_str_gene("aaabraabbbere")]
['a', 'b', 'r', 'a', 'b', 'e', 'r', 'e']
"""
def wrapper(fun):
@wraps(fun)
def dont_repeat(*args, **kwrds):
gen = fun(*args, **kwrds)
old_s = ""
while True:
try:
new_s = next(gen)
except StopIteration:
break
else:
if not equals(new_s, old_s):
old_s = new_s
yield new_s
return dont_repeat
return wrapper
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del