diff options
Diffstat (limited to 'Python Pipeline.wiki')
-rw-r--r-- | Python Pipeline.wiki | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/Python Pipeline.wiki b/Python Pipeline.wiki new file mode 100644 index 0000000..e91f93f --- /dev/null +++ b/Python Pipeline.wiki @@ -0,0 +1,56 @@ +{{{python +#!/usr/bin/env python3 + +import base64 +import hashlib +import os.path +import sys +from typing import Callable, Any +from dataclasses import dataclass + + +@dataclass +class Pipeline: + """ + A data pipeline. + + "Syntax" to allow functions and methods to be chained, similar to + clojures arrow operator (``->``). + + Each operation applies some kind of procedure, and forwards the + pipeline with the result (by returning a new Pipeline object with + the contained object being replaced: + + ``.do`` applies a function, passing the pipelined object as the + first value. If another position is wanted, use a lambda. + + ``.on`` Applies a method on the object. The method name needs to + be passed as a string due to how python works. + """ + + object: Any + + def on(self, proc: str, *args) -> 'Pipeline': + """Apply function to pipeline.""" + return Pipeline(getattr(self.object, proc)(*args)) + + def do(self, proc: Callable, *args) -> 'Pipeline': + """Run method in pipeline.""" + return Pipeline(proc(self.object, *args)) + + +with open(os.path.expanduser('~/.ssh/id_rsa'), 'rb') as f: + data = f.read() + +Pipeline(data) \ + .on('split', b'\n') \ + .do(lambda x: x[1:-2]) \ + .do(lambda d: b''.join(d)) \ + .do(base64.b64decode) \ + .do(hashlib.sha256) \ + .on('digest') \ + .do(base64.b64encode) \ + .do(sys.stdout.buffer.write) + +print() +}}} |