ipo_defs.html
001| """IPO Definitions.
001|
001| A "datum" is a list of ipo_token.
001|
001| Classes:
001| IPO ~Input-Process-Output base class
001|
001| ipo_token ~Inter-Process Data/Text Token class
001| ipo_function ~IPO Object base class (abstract)
001| ipo_input (ipo_function) ~IPO Input Logging class (abstract)
001| ipo_process (ipo_function) ~IPO Process Logging class (abstract)
001| ipo_output (ipo_function) ~IPO Output Logging class (abstract)
001|
001| """
002|
003| from logger import logger
004| from goodies import typename, KWARG
005|
006| Log = logger('Engine')
007|
008|
009| EOL_TAG = 'EOL'
010| SPC_TAG = 'SPC'
011|
012| SEP_TAG = 'SEP'
013|
014|
015|
016| class IPO:
017| """\
017| Input-Process-Output base class.
017|
017| An IPO instance is the engine that drives the IPO process.
017| The engine is a loop over:
017| datum_i = InputFunction()
017| datum_o = ProcessFunction(datum_i)
017| datum_x = OutputFunction(datum_o)
017|
017| If Input returns None, this signals EOF to Process.
017| If Process returns None, this signals EOF to Output.
017| If Process returns [], Output ignores the datum.
017| This allows Process to buffer and emit to Output different
017| data than it receives from Input. Process may have buffered
017| data after input ends, so the loop continues until Process
017| sends EOF to Output. This sets all three function objects'
017| status to -1 and terminates the loop.
017|
017| Properties:
017| status ~status; <0=not ready; 0=ready; >0=state
017| count ~number of records processed
017| i_obj ~Input Function instance
017| p_obj ~Process Function instance
017| o_obj ~Output Function instance
017| dmax ~Data Max limit
017| cfg ~configuration dictionary
017|
017| Methods:
017| execute ~run the IPO process
017| _status ~(property) True if all three (I/P/O) ready
017|
017| str(obj) ~pretty-print string version of object
017| repr(obj) ~JSON-like string version of object
017|
017| """
018|
019| def __init__ (self, i_obj, p_obj, o_obj, **kwargs):
020| """New IPO instance."""
021|
022| self.i_obj = i_obj
023| self.p_obj = p_obj
024| self.o_obj = o_obj
025| self.status = 0
026| self.count = 0
027|
028| self.dmax = KWARG('max', 0, int, kwargs)
029|
030| def execute (self):
031| """Execute the Input-Process-Output program."""
032| assert self.i_obj, RuntimeError('No Input object!')
033| assert self.p_obj, RuntimeError('No Process object!')
034| assert self.o_obj, RuntimeError('No Output object!')
035|
036| assert isinstance(self.i_obj, ipo_input) , RuntimeError('Invalid Input object!')
037| assert isinstance(self.p_obj, ipo_process), RuntimeError('Invalid Process object!')
038| assert isinstance(self.o_obj, ipo_output) , RuntimeError('Invalid Output object!')
039|
040|
041| datum_i = self.i_obj.start(None)
042| datum_o = self.p_obj.start(datum_i)
043| datum_x = self.o_obj.start(datum_o)
044| Log.debug()
045|
046|
047| while self._status:
048| if self.dmax and (self.dmax <= self.count):
049| break
050|
051| datum_i = self.i_obj()
052|
053| datum_o = self.p_obj(datum_i)
054|
055| datum_x = self.o_obj(datum_o)
056|
057| if self._status:
058| self.count += 1
059| Log.trace(f'[{self.count}] {datum_x!s}')
060| Log.trace()
061|
062|
063| Log.debug()
064| datum_i = self.i_obj.stop(None)
065| datum_o = self.p_obj.stop(datum_i)
066| datum_x = self.o_obj.stop(datum_o)
067|
068| @property
069| def _status (self):
070| if 0 <= self.i_obj.status: return True
071| if 0 <= self.p_obj.status: return True
072| if 0 <= self.o_obj.status: return True
073|
074| return False
075|
076| def __str__ (self):
077| """String version."""
078| names = '|'.join([self.i_obj.name,self.p_obj.name,self.o_obj.name])
079| return f'{typename(self)}: {self.count} ({self.status}) [{names}]'
080|
081| def __repr__ (self):
082| """JSON-like version."""
083| t = (typename(self), self.status, self.count)
084| return '{%s:{status:%d, count:%d}}' % t
085|
086|
087|
088| class ipo_token:
089| """Inter-Process Data/Text Token class."""
090| SPCX = ord(' ')
091| UCAX = ord('A')
092|
093| def __init__ (self, content, row, column, colname):
094| self._content = content
095| self._row = row
096| self._col = column
097| self._colname = colname
098|
099| @property
100| def row (self): return self._row
101|
102| @property
103| def col (self): return self._col
104|
105| @property
106| def colname (self): return self._colname
107|
108| def __bool__ (self): return True if 0<len(self._content) else False
109|
110| def __len__ (self): return len(self._content)
111|
112| def __call__ (self, value=None):
113| """Get/Set token value."""
114| if value is not None:
115| self._content = value
116| return self._content
117|
118| def __repr__ (self):
119| def cleaner (ch):
120| if isinstance(ch,bytes) or isinstance(ch,int):
121| return f'{ch:02x}'
122| cx = ord(ch)
123|
124| if cx < self.SPCX: return f'^{chr(self.UCAX+cx-1)}'
125|
126| if cx == self.SPCX: return '_'
127| return ch
128|
129| out = map(cleaner, self._content)
130| val = ''.join(out)
131|
132|
133| return f'[{self._row},{self._col}] {val}:{self._colname}'
134|
135|
136|
137| class ipo_function:
138| """\
138| IPO Function base class (abstract).
138|
138| This is the base class for all IPO Input, Output, and Process objects.
138| It sets the count and status attributes and increments the counter.
138| It also provides the str and repr methods.
138|
138| Properties:
138| name ~name of instance (not a filename)
138| status ~status; <0=not ready; 0=ready; >0=state
138| count ~number of records
138| cols ~column configuration list
138|
138| Methods:
138| start ~initialize object (load data if necessary)
138| stop ~terminate object (save data if necessary)
138|
138| obj() ~execute object function
138| str(obj) ~pretty-print string version of object
138| repr(obj) ~JSON-like string version of object
138|
138| """
139| tag = 'abstract'
140|
141| def __init__ (self, name:str, **kwargs):
142| """New IPO Object instance."""
143| self.name = name
144| self.status = -1
145| self.count = 0
146| self.cols = []
147|
148| def start (self, datum):
149| """Initialize this object."""
150| Log.debug(f'START: {self.name}')
151| self.status = 0
152| self.count = 0
153| return datum
154|
155| def stop (self, datum):
156| """Terminate this object."""
157| Log.debug(f'STOP: {self.name}')
158| return datum
159|
160| def __call__ (self):
161| """Execute this object's function. [OVERRIDE in subclass!]"""
162|
163| self.count += 1
164| return None
165|
166| def __str__ (self):
167| """String version."""
168| return f'[{self.status}] {self.name}:{self.tag} ({typename(self)}) {self.count} records processed'
169|
170| def __repr__ (self):
171| """JSON-like version."""
172| t = (typename(self), self.name, self.tag, self.status, self.count)
173| return '{%s:{name:"%s", tag:"%s", status:%d, count:%d}}' % t
174|
175|
176|
177| class ipo_input (ipo_function):
178| """IPO Input base class. (abstract; Do NOT Instantiate!)"""
179| tag = 'input'
180|
181| def __init__ (self, name:str, **kwargs):
182| """New IPO Input instance."""
183| super().__init__(name, **kwargs)
184| Log.trace(f'NEW INPUT: {self.name}')
185|
186| def __call__ (self, datum=None):
187| """Return next chunk of data. [OVERRIDE in subclass!]"""
188| super().__call__()
189| Log.trace(f'IN[{self.count}]: {datum!s}')
190| return datum
191|
192|
193|
194| class ipo_process (ipo_function):
195| """IPO Process base class. (abstract; Do NOT Instantiate!)"""
196| tag = 'process'
197|
198| def __init__ (self, name:str, **kwargs):
199| """New IPO Process instance."""
200| super().__init__(name, **kwargs)
201| Log.trace(f'NEW PROCESS: {self.name}')
202|
203| def __call__ (self, datum):
204| """Process a chunk of data. [OVERRIDE in subclass!]"""
205| super().__call__()
206| Log.trace(f'PROC[{self.count}]: {datum!s}')
207| return datum
208|
209|
210|
211| class ipo_output (ipo_function):
212| """IPO Output base class. (abstract; Do NOT Instantiate!)"""
213| tag = 'output'
214|
215| def __init__ (self, name:str, **kwargs):
216| """New IPO Output instance."""
217| super().__init__(name, **kwargs)
218| Log.trace(f'NEW OUPUT: {self.name}')
219|
220| def __call__ (self, datum):
221| """Write a chunk of data. [OVERRIDE in subclass!]"""
222| super().__call__()
223| Log.trace(f'OUT[{self.count}]: {datum!s}')
224| return self.count
225|
226|
227|
228| if __name__ == '__main__':
229| print()
230| ipo_in = ipo_input('an Input')
231| ipo_proc = ipo_process('a Process')
232| ipo_out = ipo_output('an Output')
233| ipo_obj = IPO(ipo_in, ipo_proc, ipo_out)
234| print(ipo_in)
235| print(ipo_proc)
236| print(ipo_out)
237| print(ipo_obj)
238| print()
239|
240| """eof"""
241|