aboutsummaryrefslogtreecommitdiff
path: root/Python Pipeline.wiki
diff options
context:
space:
mode:
authorHugo Hörnquist <hugo@lysator.liu.se>2023-06-25 06:41:04 +0200
committerHugo Hörnquist <hugo@lysator.liu.se>2023-06-25 06:41:04 +0200
commit3af714e89059739f365c3a92c8833864665ff497 (patch)
tree6c64dea8648cf7e81a437a0c9aa9678988d258c0 /Python Pipeline.wiki
parentlör 24 jun 2023 17:53:25 CEST (diff)
downloadwiki-public-3af714e89059739f365c3a92c8833864665ff497.tar.gz
wiki-public-3af714e89059739f365c3a92c8833864665ff497.tar.xz
sön 25 jun 2023 06:41:04 CEST
Diffstat (limited to 'Python Pipeline.wiki')
-rw-r--r--Python Pipeline.wiki56
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()
+}}}