Source code for decorators
# labtools, Copyright (C) 2017 Jerry Fowler and Paul Scheet.
# This program comes with ABSOLUTELY NO WARRANTY. It is licensed under
# GNU GPL Version 3. License and warranty may be viewed in the manual.
'''
Some decorators I expect to use regularly
'''
import os
import sys
from labtools import const
from labtools import labexceptions
[docs]def abstractmethod(method):
'''Declare a method 'abstract' in something vaguely like the java sense
for an abstract class or interface. Usage:
>>> @abstractmethod
>>> def method_to_be_declared_abstract(): pass
'''
def default_abstract_method(*args, **kwargs):
raise NotImplementedError('call to abstract method ' + repr(method))
default_abstract_method.__name__ = method.__name__
return default_abstract_method
[docs]def progress_bar_runner(function, counter=0, linewidth=100, perdot=1, stream=sys.stderr):
"""
Decorate the execution of a loop with printed dots to indicate progress
*function* is a method that returns a boolean to indicate whether or not to
continue. Standard while-loop semantics apply. True means continue, False means stop.
"""
if perdot < 1 or linewidth < 1:
raise labexceptions.ProgrammingFlawWarning('perdot={}, linewidth={}. Both must be positive'.
format(perdot, linewidth))
linemodulus = linewidth*perdot
thisdict = dict({
'perdot' : perdot,
'linemodulus' : linemodulus,
'counter' : counter
})
def _progress_bar(_dict_=thisdict, *args, **kwargs):
result = function(*args, **kwargs)
_dict_['counter'] += 1
thiscounter = _dict_['counter']
if not (thiscounter % _dict_['perdot']):
stream.write(const.DOT)
if not (thiscounter % _dict_['linemodulus']):
stream.write(const.NEWLINE)
return result
return _progress_bar