X-Git-Url: https://gerrit.fd.io/r/gitweb?a=blobdiff_plain;f=resources%2Flibraries%2Fpython%2FIncrementUtil.py;fp=resources%2Flibraries%2Fpython%2FIncrementUtil.py;h=fca0839ac0ffbf35028761ff3004164a1792d067;hb=75eb3abbac136bd6e9fb47f595b4f7b8a8294038;hp=0000000000000000000000000000000000000000;hpb=8843893ca7531cbb2212a5ed79882909c8374381;p=csit.git diff --git a/resources/libraries/python/IncrementUtil.py b/resources/libraries/python/IncrementUtil.py new file mode 100644 index 0000000000..fca0839ac0 --- /dev/null +++ b/resources/libraries/python/IncrementUtil.py @@ -0,0 +1,74 @@ +# Copyright (c) 2021 PANTHEON.tech s.r.o. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at: +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Increment utilities library.""" + + +class ObjIncrement(object): + """ + An iterator class used to generate incremented values in each iteration + or when inc_fmt is called. + + Subclasses should override: + _incr: when a simple '+' binary operation isn't sufficient. + _str_fmt: when a simple str representation of the incremented object + isn't the proper format. + """ + def __init__(self, initial_value, increment): + """ + :param initial_value: The first value to be returned. + :param increment: Each iteration/inc_fmt call will return the previous + value incremented by this. + :type initial_value: object supporting the '+' binary operation + :type increment: object supporting the '+' binary operation + """ + self._value = initial_value + self._increment = increment + + def _incr(self): + """ + This function will be called in each iteration/inc_fmt call. Subclasses + should override this when their object is incremented differently. + The function must compute the next iterated value and store it in + self._value. + """ + self._value += self._increment + + def __next__(self): + """ + Each iteration returns the current object and stores the incremented + object (which will be returned in the next iteration). The first + iteration returns the initial value. + """ + return_value = self._value + self._incr() + return return_value + + def __iter__(self): + return self + + def _str_fmt(self): + """ + The string representation is a standard string representation of the + incremented object. Subclasses may override this for a different + string representation. + """ + return str(self._value) + + def inc_fmt(self): + """ + Return a string representation and increment the current value. + """ + return_value = self._str_fmt() + self._incr() + return return_value