<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Caffeineated Duck's Blog]]></title><description><![CDATA[I know that I don't know.]]></description><link>https://blog.samrid.me</link><generator>RSS for Node</generator><lastBuildDate>Wed, 11 Nov 2026 01:02:58 GMT</lastBuildDate><atom:link href="https://blog.samrid.me/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[I tried to put Go inside Python. A Unix socket won.]]></title><description><![CDATA[I tried Go's browser WASM target, WASI, a component, gRPC, and FFI before shipping a length-prefixed Unix socket for Python.]]></description><link>https://blog.samrid.me/go-wasm-python-unix-socket</link><guid isPermaLink="true">https://blog.samrid.me/go-wasm-python-unix-socket</guid><category><![CDATA[golang]]></category><category><![CDATA[WebAssembly]]></category><category><![CDATA[Python]]></category><category><![CDATA[wasi]]></category><category><![CDATA[software architecture]]></category><dc:creator><![CDATA[Samrid]]></dc:creator><pubDate>Mon, 13 Jul 2026 12:27:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/60c639e51679ed6f51a2820b/09984d67-f20d-4eb1-97e1-f9e82e4ed224.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>There's a dead branch in the locatr repo called <code>feat/experiment-wasip1</code>. On it, every string that crosses the border between Python and Go gets folded into a single unsigned 64-bit integer: pointer in the top half, length in the bottom.</p>
<pre><code class="language-go">const MASK uint64 = (1 &lt;&lt; 32) - 1

func copyBufferToMemory(buffer []byte) uint64 {
	bufferPtr := &amp;buffer[0]
	unsafePtr := uintptr(unsafe.Pointer(bufferPtr))

	ptr := uint32(unsafePtr)
	size := uint32(len(buffer))

	return (uint64(ptr) &lt;&lt; uint64(32)) | uint64(size)
}
</code></pre>
<p>I wrote that in August 2024, four days after locatr's initial commit. This post follows five abandoned ways to let Python call a Go library, then the Unix socket that shipped.</p>
<h2>The library and the gap</h2>
<p><a href="https://github.com/vertexcover-io/locatr">locatr</a> takes a plain-English description of a UI element ("search bar", "the checkout button") and returns a working selector for it. Under the hood it injects JavaScript to minify the page's DOM, hands that to an LLM, gets back an element id, and maps it to a locator your automation driver can click. Two capabilities make the whole thing go: a live browser it can evaluate JavaScript in, and an HTTPS connection to an LLM API. Keep those two in mind; they decide everything that follows.</p>
<p>I wrote locatr's first commit on August 15, 2024, at Vertexcover. The experiments in this post are mine: the initial architecture, the wasm branches, the gRPC layer, and the first IPC implementation. Teammates later hardened the IPC path into what ships today, and one of them took a swing at the FFI route I'll get to near the end.</p>
<p>The gap was visible from day one, and so was the ambition. The library is Go because our stack is Go. The people who want it write Python, because browser automation lives where Playwright, Selenium, and Appium users are. The README from that first day already lists the plan under Future Plans: "compile the core <code>BaseLocatr</code> to wasm and use wasmer for using <code>Locatr</code> in multiple languages." The plan was in the repository before the experiments began.</p>
<h2>Attempt 1: the browser target, without a browser</h2>
<p>Go's oldest WebAssembly target is <code>GOOS=js GOARCH=wasm</code>, built for running inside a JavaScript host. Its escape hatch, <code>syscall/js</code>, lets Go reach out and touch JS values. Two days after the initial commit I had locatr compiling for it.</p>
<p>The problem is in the target's name. <code>syscall/js</code> assumes a JavaScript engine on the other side; our callers have a Python interpreter. Running that artifact from Python means embedding Node or simulating enough of a JS host to fool the Go runtime, which is a strange dependency chain for a library whose pitch is "no extra moving parts."</p>
<p>That experiment left a fossil: commit <code>97d62d0</code> checks <code>main.wasm</code> straight into git, all 4,150,936 bytes of it. The artifact includes the Go runtime, garbage collector and scheduler included. Four megabytes for a locator library, committed to version control at 1:55 in the afternoon.</p>
<h2>Attempt 2: WASI Preview 1 meets the sandbox</h2>
<p>WASI was the version of the dream with a standard behind it: compile to <code>wasip1</code> (stock Go grew the target in 1.21), get a portable sandboxed binary, and run it from any language with a wasm runtime. The result should have been one artifact callable outside a JavaScript host.</p>
<p>Preview 1's system interface covers files, clocks, arguments, environment variables, randomness, stdio. No sockets. No browser, obviously. Read the locatr requirements again: an HTTPS line to an LLM and a live browser to evaluate JavaScript in. The two capabilities the library cannot exist without are precisely the ones the sandbox does not have.</p>
<p>So the sandbox gets inverted. The guest imports the missing capabilities from the host:</p>
<pre><code class="language-go">//go:wasmimport env wasiEvaluateJs
func wasiEvaluateJs(jsStrPtr uint64) uint64

//go:wasmimport env wasiHttpPost
func wasiHttpPost(urlPtr uint64, headersPtr uint64, bodyPtr uint64) uint64
</code></pre>
<p>Python implements both imports. <code>wasiEvaluateJs</code> calls <code>page.evaluate(...)</code> on the caller's Playwright page. <code>wasiHttpPost</code> calls <code>requests.post(...)</code>. The LLM client inside the Go code grew an injectable transport, because <code>net/http</code> has nothing to dial with under wasip1.</p>
<p>Then comes the ABI. The functions exposed by this prototype accept numeric values, not Go strings or structs. Every string needs the dance: Python calls the module's exported <code>malloc</code>, writes UTF-8 bytes into linear memory through a <code>uint8_view</code>, packs pointer and length into the u64 from the top of this post, and passes that. Go unpacks it and reads its own memory byte by byte through <code>unsafe.Pointer</code> arithmetic. Results travel the same way in reverse, with Python responsible for calling <code>free</code>.</p>
<pre><code class="language-python">def _to_wasm_string(self, string: str) -&gt; int:
    string_bytes = string.encode("utf-8")
    length = len(string_bytes)
    ptr = self._wasm_malloc(length)
    memory = self._wasm_memory.uint8_view(ptr)
    memory[:length] = string_bytes
    return (ptr &lt;&lt; 32) | length
</code></pre>
<p>The commit log from August 19 reads like a man bargaining with an instruction set: <code>accept combined ptr_size instead of 2 seperate ptr and size</code>, then <code>pass pointer for locatr instead of global</code>. The latter replaced a global singleton with <code>InitLocatr</code> returning:</p>
<pre><code class="language-go">uint64(uintptr(unsafe.Pointer(app)))
</code></pre>
<p>That is a Go heap pointer handed to Python as a session handle, with nothing on the Go side telling the garbage collector the object is still owed to someone.</p>
<p>Two more walls, briefly. The <code>//export</code> directives that make <code>InitLocatr</code> and <code>GetLocatorStr</code> visible to the host are a TinyGo convention; stock Go had no way to export a function to a wasm host at all until <a href="https://go.dev/doc/go1.24"><code>go:wasmexport</code> landed in Go 1.24</a>, in February 2025, six months after this branch. And the Python-side runtime was <a href="https://pypi.org/project/wasmer/">wasmer-python</a>, whose last release predates Python 3.12 entirely, with the Cranelift compiler shipped as a separate wheel.</p>
<p>The honest part: it ran. Strings crossed, the LLM answered, a locator came back. You can also see exactly where the belief gave out, because the branch froze mid-shortcut. <code>GetValidLocator</code>, the step that's supposed to test candidate selectors against the real DOM, ends in <code>return locators[0]</code> with the actual <code>querySelectorAll</code> loop sitting above it, commented out.</p>
<p>Every future feature had the same price sheet: one more hand-rolled host function, one more u64-packing ceremony on both sides of the wall. August 19 was the branch's last commit.</p>
<h2>WIT described the boundary I had hand-built</h2>
<p>Everything ugly about that branch has a first-class answer in WASI Preview 2's component model. Interfaces are declared in WIT, a typed IDL, and I know because I wrote one:</p>
<pre><code class="language-wit">interface host {
    evaluate-js: func(code: string) -&gt; result&lt;string, string&gt;;
}

interface guest {
    init-locator: func(config: llm-config) -&gt; result&lt;locatr, string&gt;;

    resource locatr {
      get-locator-str: func(user-req: string) -&gt; result&lt;string, string&gt;;
    }
}

world locatr {
    import host;
    export guest;
}
</code></pre>
<p>WIT gives the boundary strings, typed errors, and a <code>locatr</code> resource with methods. The wasip1 branch had represented that resource by smuggling a raw pointer through a u64. The <code>world</code> also declares the capability contract explicitly: this component imports <code>evaluate-js</code> from whoever hosts it. It is the hand-built architecture written down as an interface.</p>
<p>The catch, in August 2024: Go could not emit components. The mature bindings lived in Rust, so the prototype did too. It used <code>wit-bindgen</code> 0.30 on the guest side and wasmtime's Python package on the host. Its entire business logic was a stub returning <code>Ok("Dummy locator string")</code>. The interface worked, but adopting it meant rewriting a working Go library in Rust for a cleaner boundary.</p>
<p>That prototype directory still exists on my disk. It has a <code>.git</code> folder and zero commits.</p>
<h2>gRPC, and the FFI branch</h2>
<p>Between the wasm attempts and the thing that shipped, two more doors got opened. On August 27 I added a gRPC server with response caching: it worked, and it also meant a proto toolchain, codegen on both sides, and service lifecycle management for what is conceptually a local function call. It got parked. That November a teammate opened a branch titled <code>wip: ffi</code>, the classic route: compile Go to a C shared library, load it from Python over ctypes. Two garbage collectors sharing a border crossing, a per-OS build matrix, and cgo in the loop. It never merged.</p>
<h2>The Unix socket that shipped</h2>
<p>The commit that ended the experiments is dated October 22, 2024: <code>refactor plugin logic and add experimental ipc support</code>. Teammates then did the unglamorous work that makes something real: separating the IPC layer, adding cached plugin support, wiring in Selenium and Appium.</p>
<p>The shipped design is almost aggressively boring. Python keeps the browser, because it already has one: whatever Playwright or Selenium session the user's script owns. The Go side runs as a separate process listening on a Unix domain socket, and connects to that same browser over CDP. Messages are JSON with a 4-byte big-endian length prefix and a 3-byte version handshake. A map from client id to locatr instance replaces the pointer-as-handle trick.</p>
<p>The Go process keeps real <code>net/http</code> and a real CDP client, so neither capability has to be imported through a wall. The interface is length-prefixed JSON, with <code>encoding/json</code> as the ABI on the Go side. The operating system supplies the process boundary. Distribution becomes one static Go binary per target OS, using the project's existing build tooling. The socket won because it put no artificial boundary between the library and the capabilities it needed.</p>
<h2>Would I take the detour again?</h2>
<p>The toolchain has changed since the experiment. <a href="https://go.dev/blog/wasmexport"><code>go:wasmexport</code> shipped in Go 1.24</a>, and <a href="https://tinygo.org/docs/guides/webassembly/wasi/">TinyGo supports both wasip1 and wasip2</a>. A new attempt would not start with exactly the same compiler limitations.</p>
<p>The sharper lesson is architectural. locatr needs a browser and a network line. Once the guest imports "evaluate JavaScript in the caller's browser" and delegates HTTPS back to the host, much of the intended isolation has moved outside the module. For this library, a subprocess on a socket gave up little isolation that the WASI prototype had actually retained.</p>
<p>The branches are all still up: <a href="https://github.com/vertexcover-io/locatr/tree/feat/experiment-wasip1">feat/experiment-wasip1</a>, with the pointer-packing, the commented-out validator, and the 4 MB wasm binary in its history.</p>
<hr />
<p><em>locatr is open source at</em> <a href="https://github.com/vertexcover-io/locatr"><em>github.com/vertexcover-io/locatr</em></a><em>. Samrid Pandit is a backend engineer at CrowdVolt . Reach him at <a href="mailto:hello@samrid.me">hello@samrid.me</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[There are no images in π (I found some anyway)]]></title><description><![CDATA[I turned ten million digits of pi into a 24.5 MiB perceptual index and searched 1.4 million fragments in a browser, with checksums and receipts.]]></description><link>https://blog.samrid.me/images-in-pi-search-engine</link><guid isPermaLink="true">https://blog.samrid.me/images-in-pi-search-engine</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[cloudflare]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[Computer Vision]]></category><dc:creator><![CDATA[Samrid]]></dc:creator><pubDate>Mon, 13 Jul 2026 12:24:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/60c639e51679ed6f51a2820b/39b99aec-27d2-4a8c-98f9-100aff7375aa.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>π is the internet's favorite hard drive. Its decimal expansion never ends or settles into a repeating cycle. If you believe the meme, those digits contain everything: your birth certificate, the Shrek script, the photo you deleted in 2019. There's a parody filesystem called <a href="https://github.com/philipl/pifs">πfs</a> that takes the joke to its logical end. Don't store your file, <em>find</em> it in π and remember the offset. Infinite storage, zero bytes.</p>
<p>The punchline is hiding in the metadata. For a random n-digit string, the first place it shows up in π sits around 10ⁿ digits deep, so the offset you'd have to remember is about as long as the file it points to. πfs is a rename tool with extra steps, and the new name is longer than your movie.</p>
<p>There's a quieter problem underneath that one. None of it is proven. π is <em>conjectured</em> to be normal, meaning every finite digit string would appear with the expected frequency. <a href="https://www.ams.org/publicoutreach/math-history/hap-6-pi.pdf">No one has proved it</a>. Irrationality only tells us that the decimal expansion cannot terminate or become periodic; it does not prove that every digit keeps appearing forever. Every "find your birthday in π!" site is writing checks mathematicians haven't cashed.</p>
<p>I built a version with a smaller, checkable claim: <a href="https://foundinpi.com">foundinpi.com</a>. You give it an image, it excavates the closest match it can assemble out of actual digits of π, and it hands you back a scored, named <em>relic</em> with a public museum page and a receipt that says exactly which digits were searched. <a href="https://github.com/CaffeineDuck/foundinpi">The source is public</a>.</p>
<p>Every layer below is mine: the digit generation, the index format, the search algorithm, the scoring economy, and the edge deployment. This post is about what that took: computing ten million digits from scratch, packing them into a 24.5 MiB binary index, then running a nearest-neighbor search over 1.4 million fragments inside a Web Worker on your phone.</p>
<h2>The honesty contract</h2>
<p>Every π-storage gag falls apart the same way: "somewhere in π" is unfalsifiable. <em>Somewhere</em> is doing all the work. If a site claims your selfie lives at offset 400 trillion, you can't check, they can't check, and the claim is worth nothing.</p>
<p>So the first design decision was to shrink the claim until it became checkable, and then never exceed it. The search covers a <em>dig site</em>, a declared, finite, reproducible slice of π:</p>
<ul>
<li><p>Dig Site I: the first 1,000,000 decimal digits (the default)</p>
</li>
<li><p>Dig Site II: the first 10,000,000 decimal digits (opt-in, heavier)</p>
</li>
<li><p>Dig Site III: the first 1,000,000 <em>hexadecimal</em> digits</p>
</li>
</ul>
<p>Every published relic carries its receipt: which dig site, how many digits, which index version, and the SHA-256 of the exact index file that produced the match. The README calls this the honesty contract. Those fields live in the relic's schema, so every stored relic has a receipt.</p>
<p>Declaring the limits had a useful side effect. Once everyone searches the same fixed haystack, scores become comparable. The museum ranks every result against a named index with a fixed checksum.</p>
<h2>First, obtain one million digits</h2>
<p>You can download π digits from a dozen places, but then your receipt starts with "trust this text file I found." The build script generates them instead, using plain Node, BigInt, and no numerical dependency.</p>
<p>The generator uses the Chudnovsky formula with binary splitting. Its core recursively combines large integer terms and computes an integer square root with Newton's method. The term count starts with one constant:</p>
<pre><code class="language-js">const digitsPerTerm = 14.181647462725477;
</code></pre>
<p>Every term of the Chudnovsky series buys about 14.18 more correct digits, so ten million digits costs roughly 705,000 terms. Binary splitting keeps the intermediate numbers from exploding, BigInt does the rest, and the script writes two files: the packed index, plus a manifest recording the digit count, the descriptor layout, and a SHA-256 checksum. That checksum is pinned in the app's source and printed on every relic.</p>
<p>The app contains a second π algorithm. If the index file cannot load, as can happen during local development before assets are built, the browser computes 6,144 digits with Machin's arctangent formula. John Machin used that formula in 1706 to calculate π to 100 decimal places by hand. The fallback lives in <code>src/lib/excavation/pi.ts</code>.</p>
<h2>Turning digits into something you can match</h2>
<p>Here's the problem with "finding" an image in π: a compressed image is a long byte string, and an exact match is outside the useful range of a browser-sized search. A finite index needs a representation that can return an honest near match.</p>
<p>So the matching happens on appearance instead of bytes. The browser draws the image onto a canvas and cuts it into tiles. Tile size adapts to produce roughly a 32×32 grid, clamped between 10 and 28 pixels. Each tile becomes an average color and a 4×4 luma thumbnail. π is summarized into the same shape ahead of time.</p>
<p>The precomputed half is the index. Take the digit stream, slide a 32-digit window across it with a stride of 7, and describe every window as if it were a tiny image patch:</p>
<ul>
<li><p>digits 1–9 → three 3-digit groups, mod 256 → an RGB color</p>
</li>
<li><p>digits 10–25 → sixteen digits, one per cell of a 4×4 brightness grid, rescaled from 0–9 to 0–15, packed two cells per byte</p>
</li>
<li><p>seven derived stats, one byte each: contrast, total ink, horizontal / vertical / diagonal edge energy, texture (mean neighbor difference), center bias</p>
</li>
</ul>
<p>That's 3 + 8 + 7 = 18 bytes per fragment. One million digits yields ⌊(1,000,000 − 32) / 7⌋ + 1 = 142,853 fragments, a 2.5 MB binary. Ten million digits yields 1,428,567 fragments.</p>
<p>The hex dig site has the cleanest mapping. Two hex digits per color channel make one byte, and a single hex digit is already a 0–15 luma value. Base 10 needs rescaling; base 16 fits the descriptor directly.</p>
<p>None of this involves a model. It's the old kind of computer vision, the kind people hand-rolled before everything became an embedding: a crude perceptual hash built from a thumbnail and some gradient stats. The matcher only needs enough signal to rank tiny patches.</p>
<h2>The byte Cloudflare made me delete</h2>
<p>The v2 descriptor was originally 19 bytes. The nineteenth byte stored saturation.</p>
<p>Then I tried to deploy Dig Site II: 1,428,567 fragments × 19 bytes = 27,142,773 bytes, about 25.9 MiB. <a href="https://developers.cloudflare.com/workers/platform/limits/">Cloudflare Workers caps individual static assets at 25 MiB</a>. The deploy failed over roughly 900 KB.</p>
<p>Shrinking the dig site would weaken the search, while splitting the binary would complicate the format for one deployment limit. The stored saturation byte was the easier target. Saturation is <code>max(r,g,b) − min(r,g,b)</code>, and r, g, b were already sitting in bytes 0 through 2 of the same record. The nineteenth byte cached one subtraction. I had been paying 1.4 MB to store arithmetic.</p>
<p>Now the build writes 18 bytes and the worker recomputes saturation while building its in-memory search index, once per session, one subtraction per fragment. 1,428,567 × 18 = 25,714,206 bytes, or 24.52 MiB. Fits, with about 500 KB of headroom that I am choosing not to think about.</p>
<p>The commit, <code>fix: keep v2 dig site under asset limit</code>, changes the descriptor writer and reader, updates the format constants, and rebuilds the indexes. The rebuilt manifest records 18 bytes per descriptor.</p>
<h2>Nearest-neighbor search with no library</h2>
<p>Now the hot path. An excavation is around 1,000 tiles, and each tile needs the closest fragment out of up to 1,428,567 under a distance function that mixes eight features. Brute force lands on the order of a billion distance evaluations per image, in JavaScript, on a phone, while a progress bar pretends everything is fine.</p>
<p>This is an approximate nearest neighbor problem. The normal answer is a library: FAISS, Annoy, a vector database if you have money and a network connection. In a Web Worker, with a binary you already shipped, you build the boring version yourself out of typed arrays.</p>
<p>The worker builds three bucket families over the fragments. Each catches a different way two patches can be similar:</p>
<ul>
<li><p><strong>Color buckets</strong> — RGB high nibbles, 16×16×16 = 4,096 buckets ("roughly this color")</p>
</li>
<li><p><strong>Signature buckets</strong> — the four corners of the 4×4 luma grid, 2 bits each, 256 buckets ("roughly this shading layout")</p>
</li>
<li><p><strong>Shape buckets</strong> — quantized contrast, texture, edge direction, and center bias packed into 9 bits, 512 buckets ("roughly this kind of patch")</p>
</li>
</ul>
<p>Each family is stored CSR-style. A counting sort produces one flat <code>starts</code> array and one flat <code>items</code> array per family, so lookups are two reads and a loop. No Maps, no arrays-of-arrays; nothing in the hot path allocates.</p>
<pre><code class="language-ts">function startsFromCounts(counts: Uint32Array) {
  const starts = new Uint32Array(counts.length + 1);
  for (let i = 0; i &lt; counts.length; i += 1) {
    starts[i + 1] = starts[i] + counts[i];
  }
  return starts;
}
</code></pre>
<p>Per tile, the candidate set is the union of the 27 color buckets within radius 1 of the tile's color, the tile's exact signature bucket, and its exact shape bucket. If that union comes back with fewer than 160 candidates (dark photos land in crowded buckets, weird ones in empty buckets), the color search widens to radius 2, which is 125 buckets, and tries again.</p>
<p>Unioning buckets produces duplicates. The obvious dedup, clearing a <code>visited</code> array between tiles, would mean zeroing 1.4 million entries a thousand times per image. Instead the index keeps a generation counter:</p>
<pre><code class="language-ts">searchIndex.seenMark += 1;
// ...
function consider(candidateIndex: number) {
  if (seen[candidateIndex] === seenMark) return;
  seen[candidateIndex] = seenMark;
  // score the candidate...
}
</code></pre>
<p>Marks left over from previous tiles belong to an older generation, so they simply stop counting. Nothing is cleared during ordinary search. A reset path handles the 32-bit counter's eventual wrap, far beyond a single excavation.</p>
<p>Surviving candidates get the real distance, a weighted sum over color, signature, contrast, ink, edge energy, texture, center bias, and saturation:</p>
<pre><code class="language-ts">const distance =
  candidateColorDistance * 0.045 +
  (candidateSignatureDistanceSum / 16) * 4.9 +
  contrastDistance * 1.25 +
  inkDistance * 0.55 +
  edgeDistance * 3.2 +
  textureDistance * 1.1 +
  centerDistance * 0.8 +
  saturationDistance * 0.035;
</code></pre>
<p>Those numbers came from repeated visual tests, not a training run. The weights moved until the same test images stopped producing obviously wrong patches. The git log records the tuning plainly: <code>rebalance pi tile classes</code>, then <code>make dig-site scoring distance-sensitive</code>. The deployed weights are the constants shown above.</p>
<h2>The classifier is an economy</h2>
<p>Each matched tile gets classified by its distance: Exact Pi (≤ 17, with extra guards), Near Pi (≤ 26), Lossy Pi (≤ 33), or Earth Bytes, which means "not found in this dig site" and renders as soil.</p>
<p>An early build handed out Exact Pi too generously. When too much of an image is labelled "exact," the category stops carrying information and the toy reads as rigged. The correction is preserved in a blunt commit title: <code>make exact pi classification rarer</code>.</p>
<p>Scoring follows the same logic. A relic's score is 84% a smooth distance-quality curve, <code>((42 − d) / 28)^1.18</code> per tile, and 16% class weights, so two relics with identical class counts still rank differently when one's matches are tighter. The score maps to a rarity ladder: Cathedral Grade (82+), Museum Grade (66+), Field Relic (48+), Fragment Cluster (30+), Deep Earth below that. The server stores the resulting rarity string with the relic.</p>
<h2>Same image, same relic</h2>
<p>There is no randomness anywhere in the pipeline. Every tile's class, coordinate, distance, and source color gets folded through FNV-1a, salted with the dig-site id, into a 32-bit seed. The seed drives a name generator (12 materials × 12 forms × 12 epithets, four patterns, a serial number mod 997), so every excavation gets a name like <em>Mossglass Reliquary 042</em> or <em>Cipher of the Quiet Window 613</em>. Upload the same image to the same dig site in the same mode and you get the same relic, byte for byte, name and all. The relic is a function of the image and the declared search space.</p>
<p>Determinism also earns its keep at publish time. The server hashes the rendered PNG and a canonicalized JSON of the match stats; publishing an exact duplicate just returns the original relic's page instead of minting a copy. Below exact, a fuzzy pass runs: D1 prefilters by mode, dig site, and score within ±14, then a similarity blend (55% share-grid overlap, 20% score, 20% pi-nativeness, 5% longest-fossil) flags anything above 0.82 as a cousin. This keeps the museum from becoming fifty copies of the same test image.</p>
<p>The share grid compresses every relic to a 7×7 emoji map of its tile classes. 🟩 is exact, 🟨 near, ⬜ lossy, and ⬛ earth. The published page renders the same four classes as colored squares.</p>
<h2>A public museum with no text box</h2>
<p>An anonymous public gallery is a moderation problem, and the usual answers are report buttons and regret. A one-person toy needs a smaller attack surface.</p>
<p>So the museum has no pen. Free text never renders publicly. A relic's caption comes from ten curated <em>field stamps</em>: "museum grade", "dug by hand", "found at 3am", "do not lick", "handle with awe", "certified crunchy", "straight outta π", "lost media, found", "for science", "older than math". The server validates against the exact list and stores null for anything else. Even legacy free-text rows still sitting in D1 get dropped on both write and read. The bounded vocabulary keeps the wall unwritable.</p>
<p>The same architecture quietly solved privacy. All matching happens client-side in the worker, so your original image never leaves the device. Publishing uploads only what the app itself rendered: the π-reconstructed relic PNG and its share card. I couldn't leak your photos if I wanted to. I never have them.</p>
<h2>The boring parts that make it fast</h2>
<p>The serving stack is deliberately dull. Astro pages with one React island, on Cloudflare Workers, D1 for relic metadata, R2 for images.</p>
<p>Relic images are immutable by construction. Each publish writes to a fresh key (<code>relics/{id}/relic.png</code>) with <code>max-age=31536000, immutable</code>, so cache invalidation is solved by never invalidating anything; new content gets a new name. In front of the dynamic routes sits a small middleware that talks to the Workers cache directly: per-route TTL rules (home 5 min, museum 2 min, relic pages 5 min, artifacts a year), <code>cdn-cache-control</code> split from browser <code>max-age</code>, and <code>waitUntil</code> so writing to the cache never blocks the response. Every response carries an <code>x-foundinpi-cache: HIT|MISS|BYPASS</code> header, which turns cache debugging into <code>curl -sI</code> instead of guesswork.</p>
<p>Views needed one trick. The museum ranks by views, and the naive version costs a D1 write per pageview, so views are sampled: the client sends a weight with its beacon and the server clamps it to 64 and adds it in a single UPDATE. Approximate counts, a fraction of the writes. A toy museum does not need exactly-once view accounting.</p>
<p>Analytics runs through a first-party <code>/ingest</code> proxy on the same Worker, so the one script tag the site loads is served from its own domain.</p>
<h2>A million digits is enough to draw a cat</h2>
<p>The 25 MiB cap flushed out a redundant byte without reducing the index. In this case, a platform limit acted like a code review.</p>
<p>The finite dig site makes scores comparable, while its checksums make results reproducible. Determinism makes relics shareable and deduplicates published results. The constraints introduced for honesty now carry most of the game.</p>
<p>None of the reconstruction needs a model. A 4×4 thumbnail, gradient statistics, a counting sort, and a hand-tuned distance function can reconstruct a face out of transcendental garbage at interactive speed on a phone.</p>
<p>No one has proved that π contains every finite string. The first million digits still yield 142,853 slightly wrong colors, and that turns out to be enough to draw a cat.</p>
<p>Go dig: <a href="https://foundinpi.com">foundinpi.com</a>.</p>
<hr />
<p><em>Found in Pi is live at</em> <a href="https://foundinpi.com"><em>foundinpi.com</em></a><em>, with source at</em> <a href="https://github.com/CaffeineDuck/foundinpi"><em>github.com/CaffeineDuck/foundinpi</em></a><em>. It was designed, built, and operated solo using Astro, React, and TypeScript on Cloudflare Workers, D1, and R2. Samrid Pandit is a backend engineer at CrowdVolt. Reach him at <a href="mailto:hello@samrid.me">hello@samrid.me</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[Data Race in Python despite GIL?]]></title><description><![CDATA[It might even seem silly even to assume that GIL would let you have a condition like data race. But to understand that we'll need to understand GIL.]]></description><link>https://blog.samrid.me/data-race-in-python-despite-gil</link><guid isPermaLink="true">https://blog.samrid.me/data-race-in-python-despite-gil</guid><category><![CDATA[Python]]></category><category><![CDATA[GIL]]></category><dc:creator><![CDATA[Samrid]]></dc:creator><pubDate>Thu, 06 Apr 2023 20:14:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680810580963/b66efd22-8c92-4ef9-a59b-fa25ed96778c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-data-race">Data race</h1>
<p>While the definite definition of <strong>data race</strong> differs with the concurrency model and the language, it's safe to assume that data race is when 2 or more threads try to access the same memory where at least one of them is a write operation.</p>
<p>Seeing the above requirements, it might even seem silly even to assume that GIL (<em>Global Interpreter Lock</em>) would let you have a condition like data race. But there are nuances to it and to understand that we'll need to understand what GIL is and how it works.</p>
<p><strong><em>Note:</em></strong> <em>Python's semantics aren't tight or specific enough to definitively call something a data race vs. a race condition, so I'll avoid going too deep into its classification.</em></p>
<h1 id="heading-global-interpreter-lock-gil">Global Interpreter Lock (GIL)</h1>
<p>As the name suggests, GIL locks the <em>interpreter</em> to running only 1 thread at a time. This means it limits one thread to execute bytecode at a time or it runs <em>one bytecode instruction</em> at a time.</p>
<p>The GIL also guarantees lock is released every <code>sys.getswitchinterval()</code> second, at which point a thread switch can take place. This means that for Python code, a thread switch can still take place, but only between byte code instructions.</p>
<p>But what does <em>"one bytecode instruction at a time"</em> even mean?</p>
<h1 id="heading-bytecode">Bytecode</h1>
<p>Bytecode is the low-level representation of the Python code which is platform-independent. In simpler words, it is the <em>compiled</em> version of the code you wrote which is run by the Python interpreter. You may be confused and thinking "Isn't Python an interpreted language?", while yes you're right, that is outside the scope of this article so you can read more about it <a target="_blank" href="https://stackoverflow.com/questions/6889747/is-python-interpreted-or-compiled-or-both">here</a>.</p>
<p>Now to understand the statement "one bytecode instruction at a time", we'll need to look at the statement <code>x=x+1.</code> While it seems like a simple statement where <code>x</code>'s value is incremented by one, but at the bytecode level a simple statement is turned into multiple instructions, such as;</p>
<ol>
<li><p>Load <code>x</code> into the register</p>
</li>
<li><p>Increment <code>1</code> to the value of <code>x</code></p>
</li>
<li><p>Write the value in the register back to <code>x</code></p>
</li>
</ol>
<p><strong><em>Note:</em></strong> <em>We'll call this order of operations the "</em><code>load-modify-store</code> <em>statement' from now on.</em></p>
<p>A simple operation like incrementing a variable has to use multiple instructions. So, if threads are switched in the middle of executing an instruction, it might lead to what we know as a <em>data race.</em></p>
<h1 id="heading-how-does-data-race-occur">How does data race occur?</h1>
<p>Going back to the <code>load-store-modify</code> statement, we discussed that it might lead to a race condition. That is because, at any point in the <code>load-store-modify</code> statement, another thread might take over and run its own operation before the 3-part operation is complete, which will affect the correctness of the output of the program. Hence, it may lead to a race condition.</p>
<p>As a simple example, assume that <strong>GIL doesn't exist</strong> in this version of Python's interpreter.</p>
<pre><code class="lang-python">x = <span class="hljs-number">10</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increment</span>():</span>
    <span class="hljs-keyword">global</span> x
    x += <span class="hljs-number">1</span>

t1 = Thread(target=increment)
t2 = Thread(target=increment)

t1.start()
t2.start()

t1.join()
t2.join()
</code></pre>
<p>Now let's try to dry-run the following code; you need to keep in mind that, in data races, the code will not be deterministic hence we'll dry-run a possibility which might happen.</p>
<ol>
<li><p><code>t1</code> reads the value of <code>x</code> and stores it in a temporary variable <code>t1_x</code>,</p>
</li>
<li><p><code>t1</code> increments the value of <code>t1_x</code> by <code>1</code>,</p>
</li>
<li><p><code>t2</code> reads the value of <code>x</code> and stores it in a temporary variable <code>t2_x</code>,</p>
</li>
<li><p><code>t1</code> writes the value of <code>t1_x</code> back to <code>x</code>,</p>
</li>
<li><p><code>t2</code> increments the value of <code>t2_x</code>,</p>
</li>
<li><p><code>t2</code> writes the value of <code>t2_x</code> back to <code>x</code></p>
</li>
</ol>
<p>If you don't look at the dry run, you might assume the value of <code>x</code> to be <code>12</code>, but due to a possible data race condition, the value of <code>x</code> will be <code>11</code>. The value of <code>t1_x</code> will be overwritten as <code>t2_x</code> never knew about the <code>t1_x</code>'s value being written to <code>x</code> and only cares about the initial value of <code>x</code>.</p>
<p>You also have to remember that, the following condition isn't possible in current Python (with GIL) due to it having locks on thread switches which lasts <code>sys.getswitchinterval() seconds</code> (<em>5 milliseconds on average</em>). This means that Python won't switch threads unless an operation takes more than 5 milliseconds and as <code>x+=1</code> requires less than that to complete, so threads won't switch context and a data race won't happen.</p>
<h2 id="heading-data-race-example">Data race example</h2>
<p>While the above example can't practically demonstrate data race in Python, the following example can practically demonstrate data race on Python versions <em>below 3.10</em>.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> threading <span class="hljs-keyword">import</span> Thread
<span class="hljs-keyword">from</span> time <span class="hljs-keyword">import</span> sleep

counter = <span class="hljs-number">0</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increase</span>():</span>
    <span class="hljs-keyword">global</span> counter
    <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(<span class="hljs-number">0</span>, <span class="hljs-number">100000</span>):
        counter = counter + <span class="hljs-number">1</span>

threads = []

<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">0</span>, <span class="hljs-number">400</span>):
    threads.append(Thread(target=increase))
<span class="hljs-keyword">for</span> thread <span class="hljs-keyword">in</span> threads:
    thread.start()
<span class="hljs-keyword">for</span> thread <span class="hljs-keyword">in</span> threads:
    thread.join()

print(<span class="hljs-string">f'Final counter: <span class="hljs-subst">{counter}</span>'</span>)

<span class="hljs-comment"># Final counter: 31735072</span>
<span class="hljs-comment"># Final counter: 32829326</span>
<span class="hljs-comment"># Final counter: 31496003</span>
</code></pre>
<p>The above example works because the loop of 100,000 takes more than 5 milliseconds to complete, hence data race can be seen practically.</p>
<h1 id="heading-relation-between-race-condition-and-data-race">Relation between race condition and data race</h1>
<p>A race condition is a flaw that occurs when a program's correctness depends on the order and/or timing of the events executed. A race condition is a higher-level error than a data race. Many race conditions can be caused by data races, but this is not necessary. In summary, a data race is a specific thing that a program does, and a race condition is a flaw in the program's behaviour.</p>
<p>It's very important to understand that race condition and data race aren't the same things. They are not a subset of one another. They are also neither necessary nor sufficient conditions for one another. But in this context <code>load-modify-store</code> statement causes a data race which might lead to a race condition as well.</p>
<p>To clarify, the <code>load-modify-store</code> statement causes a data race which leads to a race condition, and that is the relationship between data race and race condition.</p>
<p><strong><em>Note:</em></strong> <em>Because access to data structures is not atomic, race conditions can take place there as well.</em></p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>The data race condition mentioned before is also known as <code>load-modify-store</code> data race. A true <strong>data race</strong> condition (same memory location being accessed and modified by our processor at the same time) isn't technically possible, most of the <strong>data race</strong> conditions happen due to cache maintenance problems.</p>
<p>Data race can be classified as a cache maintenance problem as well. If you load a value from a memory location, modify it, and then at some point write it back to the original memory location then you realize the value at the shared location prior to write-back is no longer the value you originally copied then information is potentially lost and that's where things start to go bad.</p>
<p>Data race in Python is definitely possible and GIL doesn't prevent data race as GIL only makes sure that only one thread executes bytecode at a time, which doesn't guarantee higher-level operations will be atomic, hence data race and race conditions can happen in Python.</p>
]]></content:encoded></item><item><title><![CDATA[How to convert the type of function's arguments in Python at runtime?]]></title><description><![CDATA[Converting the type of arguments passed to the function according to the type hints of the parameters of a function.]]></description><link>https://blog.samrid.me/how-to-convert-the-type-of-functions-arguments-in-python-at-runtime</link><guid isPermaLink="true">https://blog.samrid.me/how-to-convert-the-type-of-functions-arguments-in-python-at-runtime</guid><category><![CDATA[Python]]></category><category><![CDATA[functions]]></category><dc:creator><![CDATA[Samrid]]></dc:creator><pubDate>Wed, 19 Jan 2022 16:47:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1642611813493/rkAcQWSFj.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>Most of us have run into a situation where we have to change the type of a parameter in function; either it is simple <code>str</code> -&gt; <code>int</code> or something far more complex. But at some point, we'll be repeating the code too much just for converting the types of the parameter instead of actual logic which drastically increases the code length and decreases readability. </p>
<p>Example:</p>
<pre><code class="lang-py"><span class="hljs-comment"># Defining a function with Type Hints (I'll explain this below)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greater</span>(<span class="hljs-params">a: int, b: int</span>) -&gt; int:</span>
    <span class="hljs-comment"># Converting from str to int</span>
    a = int(a)
    b = int(b)
    <span class="hljs-comment"># This is equivalent of </span>
    <span class="hljs-comment"># if a &gt; b:</span>
    <span class="hljs-comment">#     return a</span>
    <span class="hljs-comment"># else:</span>
    <span class="hljs-comment">#     return b</span>
    <span class="hljs-keyword">return</span> a <span class="hljs-keyword">if</span> a &gt; b <span class="hljs-keyword">else</span>

<span class="hljs-comment"># Taking input</span>
a = input(<span class="hljs-string">'Enter a number'</span>)
b = input(<span class="hljs-string">'Enter another number'</span>)

<span class="hljs-comment"># Passing the arguements to the function</span>
greatest = greater(a, b)
print(greatest)
</code></pre>
<p>It's not that big of a problem for a single function, but assume that you're creating a python module that accepts certain data types, it'd be tiresome for users to convert the data type every time before passing to your module or you'd have to repeat your code just for converting the data types.</p>
<h1 id="heading-what-are-type-hints">What are Type Hints?</h1>
<p>Type hints in python is a way of telling python the type of data you'd want to accept and return. It is mostly used in functions, but you can use it while declaring variables as well. </p>
<h2 id="heading-why-use-type-hints">Why use Type Hints?</h2>
<ul>
<li>Using type hints will provide better autocompletion in your favorite IDE.</li>
<li>You won't have to check the documentation for knowing the return type and the data type of parameters in a function.</li>
<li>Type Hints make it easier to write and generate documentation.</li>
</ul>
<p>Python being a dynamically typed language, type hints don't interfere with the core principles of python. Type hints won't affect the running of the code during runtime. Type hinting as <code>str</code> and passing <code>int</code> is perfectly okay. </p>
<blockquote>
<p><strong>NOTE:</strong> Type hint is not something that executes. Python ignores your type hints while running your code. </p>
</blockquote>
<h2 id="heading-how-to-use-type-hints">How to use Type Hints?</h2>
<h3 id="heading-code-without-type-hints">Code without Type Hints</h3>
<pre><code class="lang-py"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">func_a</span>(<span class="hljs-params">a, b</span>):</span>
    <span class="hljs-keyword">return</span> a + b
</code></pre>
<h3 id="heading-code-with-type-hints">Code with Type Hints</h3>
<pre><code class="lang-py"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">func_a</span>(<span class="hljs-params">a: int, b: int</span>) -&gt; int:</span>
    <span class="hljs-keyword">return</span> a + b
</code></pre>
<p>Explanation:</p>
<ul>
<li><code>a: int</code> means that the parameter a needs to be a <code>int</code> type.</li>
<li><code>-&gt; int</code> means that the function <code>func_a</code> returns a value with type <code>int</code></li>
</ul>
<h2 id="heading-the-typing-python-module">The <code>typing</code> python module</h2>
<p>This module provides runtime support for type hints. The most fundamental support consists of the types Any, Union, Callable, TypeVar, and Generic. </p>
<h3 id="heading-what-is-typingany">What is <code>typing.Any</code>?</h3>
<p><code>Any</code> is a special type indicating an unconstrained type. Every type is compatible with <code>Any</code>. <code>Any</code> is compatible with every type. It is used when you don't know the exact type of data, and the type of data may be anything.</p>
<h3 id="heading-what-is-typingcallable">What is <code>typing.Callable</code>?</h3>
<p><code>Callable</code> is used to denote something that can be called. Most often, it is used to denote a function. <code>Callable[[int, int], str]</code> means that the provided function will take 2 integer arguments and return a value with the type of <code>str</code>. Checkout <a target="_blank" href="https://www.python.org/dev/peps/pep-0677/">PEP 677</a> for more info.</p>
<h3 id="heading-what-is-typingtypevar">What is <code>typing.TypeVar</code>?</h3>
<p><code>TypeVar</code> is used for creating dynamic type hints. It is mainly used by static type checkers and IDE for proper autocompletion. Check out <a target="_blank" href="https://docs.python.org/3/library/typing.html#typing.TypeVar">Python Docs</a> for more info.</p>
<blockquote>
<p>For a detailed introduction to type hints, see <a target="_blank" href="https://www.python.org/dev/peps/pep-0483/">PEP 483</a>.</p>
</blockquote>
<h1 id="heading-converting-the-type-on-runtime">Converting the type on RunTime</h1>
<h2 id="heading-creating-a-function-for-conversion">Creating a function for conversion</h2>
<p>This is a good solution, but it's only viable if there are only a few parameters in a function.</p>
<p>Example:</p>
<pre><code class="lang-py"><span class="hljs-keyword">import</span> typing <span class="hljs-keyword">as</span> t

<span class="hljs-comment"># Creating a TypeVar _T </span>
_T = TypeVar(<span class="hljs-string">'_T'</span>)

<span class="hljs-comment"># Creating a function that converts the type </span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">convert_type</span>(<span class="hljs-params">arg: t.Any, converter: _T</span>) -&gt; _T:</span>
    <span class="hljs-keyword">return</span> converter(arg)

<span class="hljs-comment"># Function that sqaures the given number</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">square</span>(<span class="hljs-params">number: t.Any</span>) -&gt; int:</span>
    <span class="hljs-comment"># Converting str -&gt; int</span>
    number = convert_type(number, int)
    <span class="hljs-keyword">return</span> number ** <span class="hljs-number">2</span>
</code></pre>
<p>Code Explanation:</p>
<ul>
<li>Created a <a target="_blank" href="https://docs.python.org/3/library/typing.html#typing.TypeVar">TypeVar</a> (<code>_T</code>). You can use <code>TypeVar</code> for dynamic type hints. <code>convert_type</code> function takes the <code>converter</code> with type <code>_T</code> and the returns value of type <code>_T</code>. So if we pass <code>str</code> in <code>converter</code>, the function would show <code>str</code> as the return value. </li>
<li>Created the function <code>convert_type</code> which accepts <code>arg</code> and <code>converter</code> as it's 2 parameters.</li>
<li>Created a function square that squares the number. But as the passed value is <code>str</code>, <code>convert_type(number, int)</code> is used to convert the number from <code>str</code> to <code>int</code>.</li>
</ul>
<p>The code seems good to use everywhere, but once we increase the number of parameters in the function, it starts to have the same problems like <strong>repetition of code</strong> and <strong>less readability</strong> as <a class="post-section-overview" href="#heading-introduction">mentioned above</a>.</p>
<h2 id="heading-creating-a-decorator-for-conversion">Creating a decorator for conversion</h2>
<h3 id="heading-what-is-a-decorator">What is a decorator?</h3>
<p>Python has an interesting feature called <a target="_blank" href="https://www.geeksforgeeks.org/decorators-in-python/">decorators</a> to add functionality to an existing code. This is also called <a target="_blank" href="https://stackoverflow.com/questions/514644/what-exactly-is-metaprogramming">metaprogramming</a> because a part of the program tries to modify another part of the program at <code>runtime</code>.</p>
<p>Simply put, decorators are just a sugar-coated version of using one function on top of another function.</p>
<h4 id="heading-code-without-decorator">Code Without Decorator</h4>
<pre><code class="lang-py"><span class="hljs-keyword">import</span> typing <span class="hljs-keyword">as</span> t

<span class="hljs-comment"># Creating a function which takes another function</span>
<span class="hljs-comment"># as the parameter</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">make_pretty</span>(<span class="hljs-params">func: t.Callable</span>) -&gt; t.Callable:</span>
    <span class="hljs-comment"># Running the passed function after printing</span>
    print(<span class="hljs-string">"I got prettier"</span>)
    func()

<span class="hljs-comment"># Defining the actual function</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_something</span>() -&gt; <span class="hljs-keyword">None</span>:</span>
    print(<span class="hljs-string">'something'</span>)

<span class="hljs-comment"># Passing the actual function inside make_pretty()</span>
make_pretty(print_something)
</code></pre>
<h4 id="heading-code-with-decorator">Code With Decorator</h4>
<pre><code class="lang-py"><span class="hljs-keyword">import</span> typing <span class="hljs-keyword">as</span> t

<span class="hljs-comment"># Creating the decorator make_pretty </span>
<span class="hljs-comment"># It takes the function automatically as the</span>
<span class="hljs-comment"># paramater if you use the @decorator syntax</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">make_pretty</span>(<span class="hljs-params">func: t.Callable</span>) -&gt; t.Callable:</span>
    <span class="hljs-comment"># This inner function takes all the arguments (args)</span>
    <span class="hljs-comment"># and keyword arguments (kwargs) passed to the </span>
    <span class="hljs-comment"># function we decorate. It can be None as well</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inner_function</span>(<span class="hljs-params">*args, **kwargs</span>):</span>
        <span class="hljs-comment"># We can do anything we want here</span>
        print(<span class="hljs-string">"I got prettier"</span>)
        <span class="hljs-comment"># Finally running the passed function</span>
        func(*args, **kwargs)
    <span class="hljs-comment"># Returning the inner function so that</span>
    <span class="hljs-comment"># decorator can use it properly</span>
    <span class="hljs-keyword">return</span> inner_function


<span class="hljs-comment"># using @make_pretty decorates print_something()</span>
<span class="hljs-comment"># function with make_pretty() function</span>
<span class="hljs-meta">@make_pretty</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_something</span>() -&gt; <span class="hljs-keyword">None</span>:</span>
    print(<span class="hljs-string">"something"</span>)

<span class="hljs-comment"># Actually running the function</span>
print_something()
</code></pre>
<p>Explanation:</p>
<ul>
<li>Usage of <code>function(*args)</code> means if we call <code>function(1, 2, 3, 4, 5)</code>, the value of the arguement <code>args</code> would be <code>(1, 2, 3, 4, 5)</code> <strong>{Tuple}</strong> and vice-versa.</li>
<li>Usage of <code>function(**kwargs)</code> means if we call <code>function(a=1, b=2, c=3)</code>, the value of the arguement <code>kwargs</code> would be <code>{a: 1, b: 2, c: 3}</code> <strong>{Dictionary}</strong> and vice-versa.</li>
<li>If nothing is passed, the values of <code>args</code> and <code>kwargs</code> will remain <code>None</code>.</li>
<li><code>@</code> is used to denote the usage of a <code>decorator</code>.</li>
</ul>
<h3 id="heading-getting-type-hints-of-a-function">Getting type hints of a function</h3>
<p>For converting the <code>argument</code> type according to the type hints in runtime, we'll have to get the type hints of the function.</p>
<pre><code class="lang-py"><span class="hljs-keyword">from</span> typing <span class="hljs-keyword">import</span> get_type_hints

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add_1</span>(<span class="hljs-params">a: int</span>) -&gt; int:</span>
    <span class="hljs-keyword">return</span> a + <span class="hljs-number">1</span>

print(get_type_hints(add_1))
</code></pre>
<p>OUTPUT:</p>
<pre><code>{<span class="hljs-string">'a'</span>: <span class="hljs-operator">&lt;</span>class <span class="hljs-string">'int'</span><span class="hljs-operator">&gt;</span>, <span class="hljs-string">'return'</span>: <span class="hljs-operator">&lt;</span>class <span class="hljs-string">'int'</span><span class="hljs-operator">&gt;</span>}
</code></pre><h3 id="heading-creating-a-decorator-for-type-conversion">Creating a decorator for type conversion</h3>
<pre><code class="lang-py"><span class="hljs-keyword">import</span> typing <span class="hljs-keyword">as</span> t

<span class="hljs-comment"># Creating a TypeVar for dynamic type hinting in the function</span>
_T = t.TypeVar(<span class="hljs-string">"_T"</span>)

<span class="hljs-comment"># Creating a function for converting type_conversion</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">type_conversion</span>(<span class="hljs-params">value: t.Any, value_type: type[_T]</span>) -&gt; _T:</span>
    <span class="hljs-comment"># If the value's type has a function named 'convert_types'</span>
    <span class="hljs-comment"># than we call the function and pass the value to it</span>
    <span class="hljs-keyword">if</span> hasattr(value_type, <span class="hljs-string">"convert_types"</span>):
        <span class="hljs-keyword">return</span> value_type.convert_types(value)
    <span class="hljs-comment"># Returning the value if it's of Any type</span>
    <span class="hljs-keyword">elif</span> value_type <span class="hljs-keyword">is</span> t.Any:
        <span class="hljs-keyword">return</span> value
    <span class="hljs-comment"># if it doesn't we return the value by forcefully</span>
    <span class="hljs-comment"># trying to convert</span>
    <span class="hljs-keyword">return</span> value_type(value)


<span class="hljs-comment"># Creating a decorator to convert types</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">convert_types</span>(<span class="hljs-params">func: t.Callable</span>) -&gt; t.Callable:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inner_function</span>(<span class="hljs-params">*args, **kwargs</span>) -&gt; t.Any:</span>
        <span class="hljs-comment"># Getting the type hints of the function</span>
        annotations = t.get_type_hints(func).copy()
        <span class="hljs-comment"># Removing the 'return' from the dictioary</span>
        <span class="hljs-comment"># as it is unnecessary right now</span>
        annotations.pop(<span class="hljs-string">"return"</span>)

        <span class="hljs-comment"># Getting only the values of annotations for</span>
        <span class="hljs-comment"># looping with the args of the function</span>
        args_annotations = annotations.values()
        new_args = list(args)

        <span class="hljs-comment"># Looping through the annotations and args</span>
        <span class="hljs-keyword">for</span> index, (arg, arg_type) <span class="hljs-keyword">in</span> enumerate(zip(args, args_annotations)):
            <span class="hljs-comment"># If arg is not of the required type, we convert it</span>
            <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> isinstance(arg, arg_type):
                new_args[index] = type_conversion(arg)

        <span class="hljs-keyword">for</span> arg_value, (arg_name, arg_type) <span class="hljs-keyword">in</span> zip(kwargs, annotations.items()):
            <span class="hljs-comment"># If arg is not of the required type, we convert it</span>
            <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> isinstance(arg_value, arg_type):
                kwargs[arg_name] = type_conversion(arg_value)

        <span class="hljs-keyword">return</span> func(*new_args, **kwargs)

    <span class="hljs-keyword">return</span> inner_function


<span class="hljs-comment"># Creating a simple function to add 1</span>
<span class="hljs-meta">@convert_types</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add_1</span>(<span class="hljs-params">a: int</span>) -&gt; int:</span>
    <span class="hljs-keyword">return</span> a + <span class="hljs-number">1</span>


<span class="hljs-comment"># Passing a string to the function</span>
print(add_1(<span class="hljs-string">"1234"</span>))
</code></pre>
<p>OUTPUT: </p>
<pre><code><span class="hljs-number">1235</span>
</code></pre><h4 id="heading-explanation-of-type-checker-code">Explanation of type checker code</h4>
<ul>
<li>We created a function <code>type_conversion</code> for converting the type of the value according to the passed required type. This function first checks if the type has a method <code>convert_types</code> and if it does, the value is passed onto that method. Else if the value is of type <code>typing.Any</code>, only the value is returned else the value is forcefully tried to convert.</li>
<li>The <code>convert_types</code> decorator gets the type hints of the function, checks if the type hints are matching with the value types, and it's not, the values' type is changed. </li>
<li><code>zip</code> function is used to combine 2 iterables. Zipping 2 tuples; <code>(1, 2, 3)</code> and <code>('a', 'b', 'c')</code> will produce a zip object with value <code>((1, 'a'), (2, 'b'), (3, 'c'))</code>.</li>
<li><code>enumerate</code> function is used to get the value and index while looping through the iterable at once. </li>
<li><code>isinstance</code> is used to check if the value is an instance of the passed class.</li>
</ul>
<h3 id="heading-making-customclass-compatible-with-type-checker">Making CustomClass compatible with type checker</h3>
<p>While it may seem like the above type checker only supports the built-in data types in python. It's not actually true. We can make our own classes compatible with the type checker by simply adding a <code>convert_types</code> <code>@classmethod</code>.</p>
<pre><code class="lang-py"><span class="hljs-keyword">import</span> typing <span class="hljs-keyword">as</span> t

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyOwnClass</span>:</span>
<span class="hljs-meta">    @classmethod</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">convert_types</span>(<span class="hljs-params">cls, value: t.Any</span>) -&gt; 'MyOwnClass':</span>
        <span class="hljs-keyword">return</span> str(value)
</code></pre>
<blockquote>
<p><strong>NOTE:</strong> Yes, you can type-hint as strings as well instead of actual objects. You can use <code>-&gt; 'int'</code> instead of <code>-&gt; int</code> as per your use case. </p>
</blockquote>
<p>Now you can type-hint your parameters with <code>MyOwnClass</code> and it'd still work. </p>
<h2 id="heading-when-not-to-use-this-decorator">When not to use this decorator?</h2>
<ul>
<li>If you have something complex like <code>t.Union</code> types; it'd be better to use <a target="_blank" href="https://pydantic-docs.helpmanual.io/">pydantic</a>.</li>
<li>If you're writing something that is time-sensitive, it'd be better to stay away from runtime type checking, or this specific implementation of runtime type checking, as it loops 2 times before even executing your function.</li>
</ul>
<h1 id="heading-resources-for-further-reading">Resources for further reading</h1>
<ul>
<li><a target="_blank" href="https://docs.python.org/3/library/typing.html">Python Typing Module</a></li>
<li><a target="_blank" href="https://realpython.com/python-type-checking/">Complete guide to python type checking</a></li>
<li><a target="_blank" href="https://www.python.org/dev/peps/pep-0483/">Detailed introduction to type hints</a></li>
</ul>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Python type hints were a game changer to developer experience ever since it was introduced in <code>python 3.5</code>. Python runtime checking is a fun topic to experiment with and might have a very wide range of use cases. But one must use it with extreme caution as it may introduce unexpected slowdowns and bugs to the code. </p>
<h1 id="heading-connect-with-me">Connect With Me</h1>
<ul>
<li><a target="_blank" href="https://github.com/CaffeineDuck">Github</a></li>
<li><a target="_blank" href="https://twitter.com/Caffe1neDuck">Twitter</a></li>
<li><a target="_blank" href="https://www.linkedin.com/in/caffeineduck/">Linkedin</a></li>
<li><a target="_blank" href="https://www.facebook.com/Samrid.pandit12/">Facebook</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Handling the fear of Asynchronous file handling in Python]]></title><description><![CDATA[Asynchronous file handling in python with aiofiles python module and asyncio as the async runtime.]]></description><link>https://blog.samrid.me/handling-the-fear-of-asynchronous-file-handling-in-python</link><guid isPermaLink="true">https://blog.samrid.me/handling-the-fear-of-asynchronous-file-handling-in-python</guid><category><![CDATA[Python]]></category><category><![CDATA[async]]></category><dc:creator><![CDATA[Samrid]]></dc:creator><pubDate>Tue, 18 Jan 2022 17:54:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1642528467852/lI72XpysF.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>Let's face it, the clock speed of our CPU doesn't really affect the performance of simple programs highly in the modern age. Things like <code>concurrency</code>, <code>multiprocessing</code> or <code>multithreading</code> are the leading factors affecting the performance of those programs. Luckily with most of the current programming languages, it's really easy to implement those features. In this article, we're going to focus more on <code>asynchronous</code>(concurrency) programming, and more specifically the overlooked part in asynchronous programming; <code>file handling</code>. </p>
<p><a target="_blank" href="https://medium.com/analytics-vidhya/multithreading-and-multiprocessing-in-python-1f773d1d160d">Click here</a> to learn more about <code>multiprocessing</code> or <code>multithreading</code></p>
<h1 id="heading-what-is-asynchronous-programming">What is Asynchronous Programming?</h1>
<p>Asynchronous code just means that the language has a way to tell the computer/program that at some point in the code, it will have to wait for <em>something else</em> to finish somewhere else. Let's say that <em>something else</em> is called "slow-file". So, during that time, the computer can go and do some other work, while "slow-file" finishes.</p>
<p>In async, every function has a protocol of saying "I will take some time doing this please continue running other things'"</p>
<p>We can think of asynchronous programming in terms of hotels and waiters. Waiters come to you and give you a menu then they go away. They periodically come to you to check if you have completed picking the food, but while you pick the food, they go to other tables and take other orders. </p>
<p>In the same way, your async program also doesn't stop doing other tasks while waiting for a function to complete, it jumps back and forth from one task to another while waiting for the tasks to complete. </p>
<h2 id="heading-why-would-you-want-to-use-async-code">Why would you want to use async code?</h2>
<p>One of the main uses of asynchronous codes is while I/O (hence the name <code>asycnio</code>). It takes around <strong>126.95 seconds</strong> to retrieve data 500 times from an API in sync code. Whereas it takes <strong>0.4880 seconds</strong> to retrieve data 500 times from an API in async code (For the same API). It's even faster and more efficient than <code>threading</code> and <code>multiprocessing</code> in the case of I/O because spawning <code>threads</code> and <code>processes</code> takes more time and resources than adding another coroutine in the <code>event loop</code>.</p>
<p><a target="_blank" href="https://towardsdatascience.com/why-you-should-use-async-in-python-6ab53740077e">Click here</a> for further reading. </p>
<h2 id="heading-async-code-examples">Async Code Examples</h2>
<h3 id="heading-awaiting-a-function">Awaiting a function</h3>
<pre><code class="lang-py"><span class="hljs-keyword">await</span> some_function()
</code></pre>
<blockquote>
<p><strong>NOTE:</strong> You can only await inside of async functions</p>
</blockquote>
<h3 id="heading-creating-an-async-function">Creating an Async function</h3>
<pre><code class="lang-py"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">some_function</span>():</span>
    ...
</code></pre>
<h3 id="heading-running-async-function-in-root-python">Running async function in root python</h3>
<pre><code class="lang-py"><span class="hljs-keyword">import</span> asyncio

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">some_function</span>():</span>
    ...

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    asyncio.run(some_function())
</code></pre>
<h3 id="heading-key-points">Key Points</h3>
<ul>
<li>Even though <code>multiprocessing</code>, <code>multithreading</code> and <code>concurrency</code> may seem similar, they are different. You can check out the link below to learn more.</li>
<li>async functions are also commonly referred to as <code>coroutines</code>.</li>
<li>asynchronous programming is also known as <code>concurrency</code>.</li>
</ul>
<p><a target="_blank" href="https://fastapi.tiangolo.com/async/#technical-details">Click here</a> for further reading.</p>
<p>Credits: <a target="_blank" href="https://www.facebook.com/n1rjal">Nirjal Paudel</a>, <a target="_blank" href="https://www.facebook.com/regmicmahesh">Mahesh C. Regmi</a></p>
<h1 id="heading-what-is-file-handling">What is File Handling?</h1>
<p>Simply put, file handling means <code>reading</code> and <code>writing</code> in the file through code (or specifically <code>python</code> in our case.) Through python, we can operate on the files. The concept of file handling is slightly different over various programming languages. In python's case, we can handle file handling with the help of the built-in function <code>open()</code>. </p>
<p>We can open files in python in various modes such as:</p>
<ul>
<li>Read (r)</li>
<li>Write (w)</li>
<li>Append (a)</li>
</ul>
<blockquote>
<p><strong>NOTE:</strong> There are a lot of other modes, you can learn about them <a target="_blank" href="https://tutorial.eyehunts.com/python/python-file-modes-open-write-append-r-r-w-w-x-etc/">here</a>.</p>
</blockquote>
<h2 id="heading-file-handling-code-examples">File Handling Code Examples</h2>
<p>Assume we have an empty file 'random.txt':</p>
<h3 id="heading-writing-content">Writing Content</h3>
<pre><code class="lang-py"><span class="hljs-comment"># Opening the file 'random.txt' in write mode</span>
<span class="hljs-keyword">with</span> open(<span class="hljs-string">'random.txt'</span>, <span class="hljs-string">'w'</span>) <span class="hljs-keyword">as</span> f:
    <span class="hljs-comment"># Writing the contents of the file</span>
    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, <span class="hljs-number">4</span>):
        f.write(<span class="hljs-string">f"hello <span class="hljs-subst">{number}</span>\n"</span>)
</code></pre>
<p>If you check 'random.txt' you'll see these contents there:</p>
<pre><code><span class="hljs-attribute">hello</span> <span class="hljs-number">1</span>
<span class="hljs-attribute">hello</span> <span class="hljs-number">2</span>
<span class="hljs-attribute">hello</span> <span class="hljs-number">3</span>
</code></pre><h3 id="heading-reading-content">Reading content</h3>
<pre><code class="lang-py"><span class="hljs-comment"># Opening the file 'random.txt' in read mode</span>
<span class="hljs-keyword">with</span> open(<span class="hljs-string">'random.txt'</span>, <span class="hljs-string">'r'</span>) <span class="hljs-keyword">as</span> file:
    <span class="hljs-comment"># Reading the contents of the file</span>
    content = file.read()
<span class="hljs-comment"># Printing the contents</span>
print(content)
</code></pre>
<p>OUTPUT:</p>
<pre><code><span class="hljs-attribute">hello</span> <span class="hljs-number">1</span>
<span class="hljs-attribute">hello</span> <span class="hljs-number">2</span>
<span class="hljs-attribute">hello</span> <span class="hljs-number">3</span>
</code></pre><p><a target="_blank" href="https://www.geeksforgeeks.org/file-handling-python/">Click here</a> for further reading.</p>
<p>You may be confused by the use of <code>with</code> while opening the file. <code>with</code> shows the usage of <code>context manager</code> in python. </p>
<h2 id="heading-what-are-context-managers">What are Context Managers?</h2>
<p>Usage of resources like file operations or database connections is very common in programming. But those resources are limited in supply. If we don't release these resources after using them, it may lead to resource leaking. This is the perfect use case for context managers, which automatically set up and teardown resources.</p>
<p><a target="_blank" href="https://www.geeksforgeeks.org/context-manager-in-python/">Click here</a> for further reading.</p>
<h1 id="heading-asynchronous-file-handing-in-python">Asynchronous file handing in python</h1>
<p>The default file handling in python is <code>synchronous</code> hence blocking. It stops the execution of the whole program while doing any operations related to the file. The bigger the file, the more resource and time intensive it is, which may severely degrade the performance of the whole program. This is where <code>asynchronous</code> file handling comes into play. </p>
<p>We're going to use <code>asyncio</code> as the asynchronous runtime provider in python, and <code>aiofiles</code> python module for asynchronous file handling. </p>
<blockquote>
<p><strong>NOTE:</strong> You need to install <code>aiofiles</code> using <code>pip install aiofiles</code> for running the code examples below.</p>
</blockquote>
<h2 id="heading-using-aiofiles">Using aiofiles</h2>
<h3 id="heading-asynchronously-reading-file-contents">Asynchronously reading file contents</h3>
<pre><code class="lang-py"><span class="hljs-comment"># Importing required modules</span>
<span class="hljs-keyword">import</span> asyncio
<span class="hljs-keyword">import</span> aiofiles

<span class="hljs-comment"># Defining the entrypoint of our asynchronous program</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    <span class="hljs-comment"># Opening random.txt with aiofiles in read mode</span>
    <span class="hljs-keyword">async</span> <span class="hljs-keyword">with</span> aiofiles.open(<span class="hljs-string">'random.txt'</span>) <span class="hljs-keyword">as</span> f:
        <span class="hljs-comment"># Asynchronously reading the files contents</span>
        contents = <span class="hljs-keyword">await</span> f.read()
    <span class="hljs-comment"># Printing the file contents</span>
    print(contents)

<span class="hljs-comment"># Explanation: https://www.freecodecamp.org/news/if-name-main-python-example/</span>
<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    <span class="hljs-comment"># Running the async function main() using asyncio</span>
    asyncio.run(main())
</code></pre>
<blockquote>
<p><strong>NOTE:</strong> You might have noticed that I haven't passed <code>r</code> as the mode. That is because <code>r</code> (read-mode) is the default mode, so we don't have to explicitly pass it every time.</p>
</blockquote>
<p>It's going to have the same output as the file handling example <a class="post-section-overview" href="#heading-file-handling-example">above</a></p>
<h3 id="heading-asynchronously-iterating-through-lines-of-the-file">Asynchronously iterating through lines of the file</h3>
<pre><code class="lang-py"><span class="hljs-comment"># Opening 'random.txt' in read mode</span>
<span class="hljs-keyword">async</span> <span class="hljs-keyword">with</span> aiofiles.open(<span class="hljs-string">'random.txt'</span>) <span class="hljs-keyword">as</span> f:
    <span class="hljs-comment"># Asynchronously iterating through the lines</span>
    <span class="hljs-keyword">async</span> <span class="hljs-keyword">for</span> line <span class="hljs-keyword">in</span> f:
        <span class="hljs-comment"># Printing each line in the file with seperator of ', '</span>
        print(<span class="hljs-string">f"New Line: '<span class="hljs-subst">{line}</span>'"</span>, sep=<span class="hljs-string">', '</span>)
</code></pre>
<blockquote>
<p><strong>NOTE:</strong> I have removed the boilerplate code of imports, defining the main function and running of the function, if you want to run the code examples, you'll have to add that yourself.</p>
</blockquote>
<p>OUTPUT:</p>
<pre><code><span class="hljs-built_in">New</span> <span class="hljs-type">Line</span>: <span class="hljs-string">'hello 1'</span>, <span class="hljs-built_in">New</span> <span class="hljs-type">Line</span>: <span class="hljs-string">'hello 2'</span>, <span class="hljs-built_in">New</span> <span class="hljs-type">Line</span>: <span class="hljs-string">'hello 3'</span>
</code></pre><h3 id="heading-asynchronously-writing-to-multiple-files">Asynchronously writing to multiple files</h3>
<pre><code class="lang-py"><span class="hljs-comment"># Importing modules</span>
<span class="hljs-keyword">import</span> asyncio
<span class="hljs-keyword">import</span> aiofiles

<span class="hljs-comment"># Creating a function that writes to files asynchronously</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">write_to_file</span>(<span class="hljs-params">filename: str, content: str</span>) -&gt; <span class="hljs-keyword">None</span>:</span>
    <span class="hljs-keyword">async</span> <span class="hljs-keyword">with</span> aiofiles.open(filename, <span class="hljs-string">"w+"</span>) <span class="hljs-keyword">as</span> f:
        <span class="hljs-keyword">await</span> f.write(content)

<span class="hljs-comment"># Creating an entry point for our async program</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    <span class="hljs-comment"># Creating an empty list of tasks</span>
    tasks = []
    <span class="hljs-comment"># Running a loop for 100 times</span>
    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> range(<span class="hljs-number">100</span>):
        <span class="hljs-comment"># Appending a coroutine of write_to_file function</span>
        <span class="hljs-comment"># to the list of tasks</span>
        tasks.append(
            asyncio.ensure_future(
                write_to_file(<span class="hljs-string">f"<span class="hljs-subst">{number}</span>.txt"</span>, <span class="hljs-string">f"File Number: <span class="hljs-subst">{number}</span>"</span>)
            )
        )
    <span class="hljs-comment"># Running all the tasks using asyncio.gather</span>
    <span class="hljs-keyword">await</span> asyncio.gather(*tasks)

<span class="hljs-comment"># Running the main() function</span>
<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    asyncio.run(main())
</code></pre>
<h4 id="heading-what-is-asyncioensurefuture">What is <code>asyncio.ensure_future</code>?</h4>
<p>The function <code>ensure_future</code> lets us execute a <code>coroutine</code> (async function) in the background, without explicitly waiting for it to finish. If we need, we can wait for it later or poll for the result. In other words, this is a way of executing code in asyncio without await. <a target="_blank" href="https://www.programcreek.com/python/example/85364/asyncio.ensure_future">Click here</a> to learn more.</p>
<h4 id="heading-what-is-asynciogather">What is <code>asyncio.gather</code>?</h4>
<p>The function <code>gather</code> lets you fire off a bunch of coroutines simultaneously. In other words, it returns the results of each coroutine (async function) passed The return value is a list of responses from each coroutine. <a target="_blank" href="https://piccolo-orm.com/blog/asyncio-gather/">Click here</a> to learn more.</p>
<h2 id="heading-task-for-the-reader">Task for the reader</h2>
<ul>
<li>The reader can write the synchronous version of the above code and find out how the time difference between the 2 versions of code. </li>
<li>The reader can write a program to read those 100 files you just created and keep the contents of every file in a list.</li>
</ul>
<h1 id="heading-resources-for-learning-more">Resources for Learning More</h1>
<ul>
<li><a target="_blank" href="https://medium.com/velotio-perspectives/an-introduction-to-asynchronous-programming-in-python-af0189a88bbb">Aynchronous Programming in Python</a></li>
<li><a target="_blank" href="https://www.twilio.com/blog/working-with-files-asynchronously-in-python-using-aiofiles-and-asyncio">Asynchronous file handling in Python</a></li>
<li><a target="_blank" href="https://docs.python.org/3/library/asyncio.html">Python asyncio Documentation</a></li>
<li><a target="_blank" href="https://pythonawesome.com/a-curated-list-of-awesome-python-asyncio-frameworks-libraries-software-and-resources/">Awesome Python async modules</a></li>
</ul>
<h1 id="heading-conclusion">Conclusion</h1>
<p>File handling is often overlooked while doing asynchronous programming which leads to unintended slow ups as file handling is very resource and time-intensive for big files. Using <code>aiofiles</code> for file handling drastically decreases the execution time of the program due to its asynchronous nature. It does not have to block the whole program while reading a file, hence other files can be read/ write and modified in the meantime, so it's a lot faster than the default way of file handling in python.</p>
]]></content:encoded></item><item><title><![CDATA[How to save Python Objects in Redis?]]></title><description><![CDATA[Saving complex python objects in redis using aioredis as the redis client and pickle for seralizing and deserializing.]]></description><link>https://blog.samrid.me/how-to-save-python-objects-in-redis</link><guid isPermaLink="true">https://blog.samrid.me/how-to-save-python-objects-in-redis</guid><category><![CDATA[Redis]]></category><category><![CDATA[Python]]></category><category><![CDATA[#howtos]]></category><dc:creator><![CDATA[Samrid]]></dc:creator><pubDate>Mon, 17 Jan 2022 09:38:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1642407096360/dOKm_8tjI.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>In this article, you'll learn about <code>pickle</code>, <code>Redis</code>, why you would want to save <code>python objects</code> in Redis, and how you would be able to achieve that with the <strong>pros</strong>, <strong>cons</strong>, and <strong>alternatives</strong> of doing so.</p>
<h1 id="heading-what-is-redis">What is Redis?</h1>
<p> <a target="_blank" href="https://redis.io/topics/introduction">Redis</a>  (which stands for REmote DIctionary Server) is an open-source in-memory data structure store that is commonly used to implement non-relational key-value databases and caches. It is used as a caching database where the data is saved in key-value pairs. You can check  <a target="_blank" href="https://aioredis.readthedocs.io/en/latest/getting-started/">this out</a> to learn more.</p>
<h1 id="heading-what-are-python-objects">What are Python Objects?</h1>
<p>Python has been an object-oriented language since it existed. Unlike procedure-oriented programming, where the main emphasis is on functions, object-oriented programming stresses on objects.</p>
<p>An object is simply a collection of data (variables) and methods (functions) that act on those data. Similarly, a class is a blueprint for that object.</p>
<p>We can think of a class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows, etc. Based on these descriptions we build the house. House is the object.</p>
<p>As many houses can be made from a house's blueprint, we can create many objects from a class. An object is also called an instance of a class and the process of creating this object is called instantiation.</p>
<p><a target="_blank" href="https://www.geeksforgeeks.org/python-classes-and-objects/">Click here</a> if you want to learn more.</p>
<h1 id="heading-why-would-you-want-to-save-python-objects-in-redis">Why would you want to save Python Objects in Redis?</h1>
<p>Redis being a simple <code>caching server</code>, it doesn't come with many of the data types available in relational databases such as  <a target="_blank" href="https://www.postgresql.org/about/">Postgres</a>. Due to the lack of variety in data types, we may sometimes need to save <code>Python Objects</code> in the Redis server itself. </p>
<p>You may sometimes want to save nested and complex python objects in the cache, which may be hard to <code>serialize</code> and <code>deserialize</code> manually into default data types provided by <code>Redis</code>.  That is the perfect use case for directly saving python objects in redis cache.</p>
<h1 id="heading-how-to-save-python-objects-in-redis">How to save Python Objects in Redis?</h1>
<p>Redis stores everything as a string, hence we can save the python object as a binary string. One of the easiest ways to dump and load binary in Python for Python Objects is using the python module <a target="_blank" href="https://docs.python.org/3/library/pickle.html">pickle</a>.</p>
<h1 id="heading-what-is-pickle">What is Pickle?</h1>
<p>Python pickle module is used for serializing and de-serializing python object structures. The process to convert any kind of python object (list, dict, etc.) into byte streams (0s and 1s) is called <code>pickling</code> or serialization or flattening or marshaling. We can convert the byte stream (generated through pickling) back into python objects by a process called <code>unpickling</code>.</p>
<h2 id="heading-how-to-use-pickle">How to use pickle?</h2>
<pre><code class="lang-py"><span class="hljs-keyword">import</span> pickle

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name: str, age: int</span>) -&gt; <span class="hljs-keyword">None</span>:</span>
        self.name = name
        self.age = age

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>) -&gt; str:</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">f'<span class="hljs-subst">{self.name}</span> <span class="hljs-subst">{self.age}</span>'</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>() -&gt; <span class="hljs-keyword">None</span>:</span>
    person_a = Person(<span class="hljs-string">'John'</span>, <span class="hljs-number">20</span>)

    <span class="hljs-keyword">with</span> open(<span class="hljs-string">'test.pkl'</span>, <span class="hljs-string">'wb+'</span>) <span class="hljs-keyword">as</span> f:
        pickle.dump(person_a, f)

    <span class="hljs-keyword">with</span> open(<span class="hljs-string">'test.pkl'</span>, <span class="hljs-string">'rb'</span>) <span class="hljs-keyword">as</span> f:
        person_b = pickle.load(f)

    print(str(person_a), str(person_b), sep=<span class="hljs-string">'\n'</span>)
    <span class="hljs-comment"># OUTPUT:</span>
    <span class="hljs-comment"># John 20</span>
    <span class="hljs-comment"># John 20</span>


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()
</code></pre>
<h4 id="heading-explanation-of-above-code">Explanation of above code</h4>
<ol>
<li>Pickle is imported using <code>import pickle</code></li>
<li>A class named <code>Person</code> is created.</li>
<li><code>person_a</code> is created as an instance of the class <code>Person</code>.</li>
<li>'test.pkl' file is opened with <code>write-binary</code>(wb) mode.</li>
<li><code>person_a</code> object is dumped into 'test.pkl' after <code>pickling</code>.</li>
<li>'test.pkl' file is opened with <code>read-binary</code>(rb) mode.</li>
<li>Data <code>unpickled</code> from the file is loaded into the variable <code>person_b</code>.</li>
<li><code>person_a</code> and <code>person_b</code> variables are printed as strings.</li>
</ol>
<blockquote>
<p><strong>Warning:</strong> <a target="_blank" href="https://davidhamann.de/2020/04/05/exploiting-python-pickle/">The pickle module is not secure</a>. Only unpickle data you trust.</p>
</blockquote>
<h2 id="heading-how-to-use-pickle-with-redis">How to use Pickle with Redis?</h2>
<p>We're going to use a python module called <a target="_blank" href="https://aioredis.readthedocs.io/en/latest/getting-started/">aioredis</a> as our redis client. You can install it using <code>pip install aioredis</code>. </p>
<h3 id="heading-pure-redis">Pure Redis</h3>
<pre><code class="lang-py"><span class="hljs-keyword">import</span> asyncio

<span class="hljs-keyword">import</span> aioredis


<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    redis = aioredis.from_url(<span class="hljs-string">"redis://localhost"</span>)
    <span class="hljs-keyword">await</span> redis.set(<span class="hljs-string">"my-key"</span>, <span class="hljs-string">"value"</span>)
    value = <span class="hljs-keyword">await</span> redis.get(<span class="hljs-string">"my-key"</span>)
    print(value)
    <span class="hljs-comment"># OUTPUT:</span>
    <span class="hljs-comment"># value</span>


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    asyncio.run(main())
</code></pre>
<h4 id="heading-explanation-of-above-code">Explanation of Above Code</h4>
<ol>
<li>Redis client is initialized by connecting to the <code>redis server</code> after providing the connection <code>URI</code>.</li>
<li>Value of "<em>my-key</em>" is set as "<em>value</em>" in the <code>redis server</code>.</li>
<li>Value of the key "<em>my-key</em>" is retrived from the <code>redis server</code>.</li>
</ol>
<h3 id="heading-redis-with-pickle">Redis with Pickle</h3>
<pre><code class="lang-py"><span class="hljs-keyword">import</span> asyncio
<span class="hljs-keyword">import</span> pickle

<span class="hljs-keyword">import</span> aioredis


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name: str, age: int</span>) -&gt; <span class="hljs-keyword">None</span>:</span>
        self.name = name
        self.age = age

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>) -&gt; str:</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">f'<span class="hljs-subst">{self.name}</span> <span class="hljs-subst">{self.age}</span>'</span>


<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    person_a = Person(<span class="hljs-string">'John'</span>, <span class="hljs-number">20</span>)
    pickled_person_a = pickle.dumps(person_a)

    redis = aioredis.from_url(<span class="hljs-string">"redis://localhost"</span>)
    <span class="hljs-keyword">await</span> redis.set(<span class="hljs-string">"person-a"</span>, pickled_person_a)
    value = <span class="hljs-keyword">await</span> redis.get(<span class="hljs-string">"person-a"</span>)

    unpickled_person_a = pickle.loads(value)

    print(str(person_a), str(unpickled_person_a), sep=<span class="hljs-string">'\n'</span>)
    <span class="hljs-comment"># OUTPUT:</span>
    <span class="hljs-comment"># John 20</span>
    <span class="hljs-comment"># John 20</span>


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    asyncio.run(main())
</code></pre>
<h3 id="heading-key-points">Key Points</h3>
<ul>
<li>The above code is <code>asynchronous</code> if you don't know about asynchronous programming. Please check <a target="_blank" href="https://medium.com/velotio-perspectives/an-introduction-to-asynchronous-programming-in-python-af0189a88bbb">this out</a>.</li>
<li>Don't set the <code>decode_responses</code> keyword-argument <code>True</code> while initializing <code>aioredis</code> client. I will write a detailed blog explaining why you shouldn't do this soon enough.</li>
<li>In the Redis example, we're not saving the <code>pickled</code> objects in file, rather we're saving it in the redis-server so we don't have to open some file and write/ read from them. </li>
</ul>
<h1 id="heading-alternatives-to-pickle">Alternatives to Pickle</h1>
<p>If you can cache your object in other ways while implementing the data structures and types available in Redis, you should use it instead of <code>pickle</code>.</p>
<p>One alternative is to convert the python object into JSON and save it. It can be done by using the <code>json</code> module. You'd have to convert the python object into a dictionary using the <code>vars</code> built-in method. After that you can use the <code>json.loads</code> and <code>json.dumps</code> functions to dump and load the dictionary. <a target="_blank" href="https://pythonexamples.org/convert-python-class-object-to-json/">Click here</a> to learn more.</p>
<p>You can check this <a target="_blank" href="https://stackoverflow.com/questions/15219858/how-to-store-a-complex-object-in-redis-using-redis-py">thread</a> on various alternatives for storing python objects in Redis.</p>
<h1 id="heading-vulnerabilities-that-come-with-using-pickle-and-redis">Vulnerabilities that come with using Pickle and Redis</h1>
<p>What is actually happening behind the scenes while <code>unpickling</code> is that the byte-stream created by <code>pickle.dumps</code> contains opcodes that are then one-by-one executed as soon as we load the pickle back in. For this reason, it's really easy to create a vulnerable app. <code>unpickling</code> is almost equivalent to using <code>eval()</code> so if your Redis server is compromised, your whole app would be compromised. You can check <a target="_blank" href="https://davidhamann.de/2020/04/05/exploiting-python-pickle/">this out</a> to learn more.</p>
<p>Credits: <a target="_blank" href="https://www.facebook.com/regmicmahesh">Regmi C. Mahesh</a></p>
<h1 id="heading-conclusion">Conclusion</h1>
<p><code>pickle</code> is a great tool for storing python objects in <code>Redis</code>, but it comes with its own drawbacks. Pickle would be perfect if you're only looking to store python objects in Redis quick and easy. You're recommended to not use it in a production environment unless you have checked out other alternatives and weighed the pros and cons of using pickle. In conclusion, I would recommend you check out <a target="_blank" href="https://www.reddit.com/r/Python/comments/2gptxg/saving_a_python_object_in_redis/">other alternatives</a> and decide which would be perfect for your use case.</p>
]]></content:encoded></item><item><title><![CDATA[Creating a Python Module for Nepal Stock Exchange API]]></title><description><![CDATA[Nepal stock exchange has been gaining a lot of traction lately. Seeing that, I was interested so I created my API Wrapper for NEPSE API.]]></description><link>https://blog.samrid.me/creating-a-python-module-for-nepal-stock-exchange-api</link><guid isPermaLink="true">https://blog.samrid.me/creating-a-python-module-for-nepal-stock-exchange-api</guid><category><![CDATA[api]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Samrid]]></dc:creator><pubDate>Mon, 14 Jun 2021 09:51:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1623662058604/cRm10gmen.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="introduction">Introduction</h1>
<p>Nepal stock exchange has been gaining a lot of traction lately. I was interested so I wondered if I could get data for my <a target="_blank" href="https://github.com/samrid-pandit/peacebot">discord bot</a>. I found a project <a target="_blank" href="https://github.com/pyFrappe/nepse/">nepse</a>, but I was not fond of that module. </p>
<h3 id="why-i-disliked-nepsehttpsgithubcompyfrappenepse-module">Why I disliked <a target="_blank" href="https://github.com/pyFrappe/nepse/">nepse</a> module</h3>
<ul>
<li>The module was <code>synchronous</code> hence blocking</li>
<li>The module returned data in <code>dict</code></li>
<li>The module returned data in <code>camelCase</code></li>
<li>The codebase was not properly managed</li>
<li>There was no proper documentation</li>
</ul>
<p>Hence, I decided to create my own <strong>NEPSE API</strong> <a target="_blank" href="https://github.com/samrid-pandit/nepse-api">Wrapper</a>.</p>
<h3 id="how-nepse-apihttpsgithubcomsamrid-panditnepse-api-will-be-better-than-nepsehttpsgithubcompyfrappenepse">How <a target="_blank" href="https://github.com/samrid-pandit/nepse-api">nepse-api</a> will be better than <a target="_blank" href="https://github.com/pyFrappe/nepse/">nepse</a></h3>
<ul>
<li>It will be <code>asynchronous</code></li>
<li>It will return data as an <code>object</code></li>
<li>It will return the data in <code>snake_case</code></li>
<li>Its codebase will be properly managed</li>
<li>It will have proper documentation</li>
<li>It will fetch data from API rather than scraping,</li>
<li>It will be type-hinted.</li>
</ul>
<h1 id="my-experience">My Experience</h1>
<h2 id="how-i-started">How I started</h2>
<p>I got started on my journey of getting <strong>Github Stars</strong>. I thought about how I was going to code it, and about my directory structure. I looked at other <code>API Wrappers</code> and got the basic idea about my code/ directory structure from there. </p>
<p><strong>The roadmap I created:</strong></p>
<h3 id="1-creating-python-class-for-storing-the-data-returned-by-api">1. Creating python class for storing the data returned by API</h3>
<p>It's not the best way, but I just simply started creating <code>Python Classes</code> with the <code>@dataclass</code> decorator by looking at what the API returned. Some of the fields were <code>null</code> so it was a hassle to determine their data type; in the end, I just used the <code>Any</code> data type from the <code>typing</code> module. The attributes weren't that consistent so it was a hassle overall.</p>
<h3 id="2-creating-various-handlers-for-getting-various-types-of-data-like-company-data-broker-data-market-data-etc">2. Creating various handlers for getting various types of data like company data, broker data, market data, etc</h3>
<p>I got the inspiration from other API wrappers that I had seen in general. I created a <code>MarketClient</code>, <code>SecurityClient</code>, and <code>BrokerClient</code> to get the market data, company data, and broker data respectively. Doing this was a good decision in my opinion because this made my codebase a bit more organized and easier to maintain.</p>
<h3 id="3-creating-a-caching-system-so-that-the-user-has-the-ability-to-either-cache-or-fetch-real-time-data">3. Creating a caching system so that the user has the ability to either cache or fetch real-time data</h3>
<p>I got the inspiration of doing this from <a target="_blank" href="https://github.com/rapptz/discord.py">discord.py</a>. I had recently figured out proper ways of caching. I used <a target="_blank" href="https://pypi.org/project/cachetools/">cachetools</a> for caching. I was very excited and made caching non-customizable. But After talking with <code>@Santosh#2138</code> I figured out it was a bad idea to not provide the user with the choice to control caching. I fixed it and gave the user the choice to change the <code>cache_retain_time</code> and <code>cache_size</code> during initialization.</p>
<h3 id="4-making-sure-that-the-code-is-fully-asynchronous-and-is-not-blocking">4. Making sure that the code is fully asynchronous and is not blocking</h3>
<p>Just using <code>async/ await</code> doesn't mean your code is automatically asynchronous. The code still might be blocking, so I had to make sure everything was asynchronous and nothing was blocking, because if that were the case; my main motive for making this <strong>API Wrapper</strong> would have failed. I accomplished it by using <code>httpx.AsyncClient</code> instead of <code>requests</code> for fetching the data from an API. </p>
<h3 id="5-converting-the-camelcase-to-snakecase">5. Converting the <code>camelCase</code> to <code>snake_case</code></h3>
<p>One of my motives for creating this <strong>API Wrapper</strong> was to make it more pythonic by having the data returned in <code>snake_case</code> rather than <code>camelCase</code>. I had to think of something creative for this because API returned the data in <code>camelCase</code>. I thought of using <code>regex</code> but I thought it would be too slow. I created a <em>monstrous</em> converter but later I figured out that using <code>regex</code> would make my code more maintainable and the performance gain won't be that noticeable, so I used the python module <code>pyhumps</code> (which uses regex) in the end for converting <code>camelCase</code> to <code>snake_case</code>.</p>
<h3 id="6-creating-tests-for-testing-my-module">6. Creating tests for testing my module</h3>
<p>I had heard about <code>unit testing</code>, but I wasn't that familiar with it. I installed <code>pytest</code> to get started with it. But shortly I figured out that you need to do a bit of extra work to run pytest in <code>async code</code>. You can learn more about <code>async code</code> unit testing <a target="_blank" href="https://promity.com/2020/06/03/testing-asynchronous-code-in-python/">here</a>. </p>
<p>Basically you need to <code>pip install pytest-asyncio</code> and your code should be like this: </p>
<pre><code class="lang-py"><span class="hljs-meta">@pytest.mark.asyncio</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_coroutine</span>():</span>
    res = <span class="hljs-keyword">await</span> long_computation()
    <span class="hljs-keyword">assert</span> res == <span class="hljs-string">"DONE"</span>
</code></pre>
<h3 id="7-formatting-the-code">7. Formatting the code</h3>
<p>I used <code>black</code> for code formatting and <code>isort</code> for import sorting. These tools are very good and these make your code much more readable and elegant. I have been in love with these tools ever since I started using them. I would highly recommend you to use it as well.</p>
<h3 id="8-creating-documentation">8. Creating Documentation</h3>
<p>As this was my first time creating a python package, I had no idea at all about creating documentation, but google and youtube had my back. I wrote doc-strings in <a target="_blank" href="https://stackoverflow.com/questions/3898572/what-is-the-standard-python-docstring-format">Google Docstring Fomat</a>. I used <a target="_blank" href="https://www.sphinx-doc.org/">sphinx</a> to generate <code>auto-docs</code> from my code and used <code>restructured text</code> for the documentation. You can check out the live version of my documentation <a target="_blank" href="https://nepse-api.readthedocs.io/">here</a></p>
<h3 id="9-publishing-module-to-pypi">9. Publishing module to <strong>PyPi</strong></h3>
<p><a target="_blank" href="https://pypi.org/">PyPi</a> is a repository of python modules for the Python programming language. If you publish your package here as <code>something-you-made</code>, people all over the world can install your package by just doing <code>pip install something-you-made</code>. I had firstly used <code>pipenv</code> for dependencies management, and <code>setup.py</code> for publishing the package, but after I found out about <a target="_blank" href="https://python-poetry.org/">Python Poetry</a>; my life has been so much easier. It makes it very easy to manage dependencies for your package and publish it in <strong>PyPi</strong> as well.</p>
<h3 id="10-managing-open-source-project">10. Managing open source project</h3>
<p>Even though I am a huge advocate of open source projects, there are problems that you face while maintaining these projects. But now there are many tools in place to help you manage open source projects easily. <a target="_blank" href="https://github.com/features/actions">Github Actions</a> is one of them. You can have various checks, tests that run automatically when an event is triggered such as <code>pull request</code> or <code>code push</code>. You can create a <code>CODE_OF_CONDUCT</code>, and proper contributing guides, issue labels, and projects to efficiently manage your open source project.</p>
<h2 id="problems-i-faced-along-the-way">Problems I faced along the way</h2>
<h3 id="api-not-found">API Not Found</h3>
<p>I started working but immediately after starting, I faced my very first hurdle. I was not able to find an API for getting the data about the Nepal stock exchange. But after struggling for some time, I figured out the API by looking at the <code>network</code> tab of <strong>dev tools</strong>. </p>
<h3 id="asynchronous-code">Asynchronous code</h3>
<p>I got started on my journey to getting Github stars. But the hurdles wouldn't stop. I had boldly claimed about making an <code>asynchronous</code> module. But I didn't have much experience with asynchronous coding. But countless hours of StackOverflow, Googling, and Python discord server surfing really did help me. If you want a full guide on this, <strong>I may create a blog related to this.</strong></p>
<h3 id="caching">Caching</h3>
<p>I used <a target="_blank" href="https://pypi.org/project/cachetools/">cachetools</a> for caching, but I was not sure which type of caching would be the best. I played around with <code>LRU</code> (Least Recently Used) caching method. But <code>LRU</code> had a fatal flaw for my use case. I wanted the cache to expire because the data was very volatile, but <code>LRU</code> wouldn't be able to suffice that. So, I decided to use <code>TTL</code> (Time To Live) caching method. Using <code>TTL</code> meant that the cache would expire so which was perfect for my use case.</p>
<h3 id="legal-issues">Legal issues</h3>
<p>I don't know much about the IT policy or cyber laws of Nepal. So, when I heard that legal action could be taken against me just for making that python module, I was scared. But later I found out that, I won't be in any trouble because the API was public, and I had given reference and copyright to NEPSE for their data, and have never claimed their data as mine. A lesson for everyone to <strong>fact-check</strong> everything before believing anything blindly.</p>
<h2 id="problems-i-havent-been-able-to-solve">Problems I haven't been able to solve</h2>
<h3 id="getting-live-market-data">Getting live market data</h3>
<p>Even though I was able to get the market data for a company from <a target="_blank" href="https://newweb.nepalstock.com/api/">New NepalStock Site</a>, it just wasn't possible to get real-time market data from that site. The data there updated very slowly and real-time data was not much found there. While searching for the solution for this problem, I discovered <a target="_blank" href="https://www.fiscalnepal.com/2020/12/28/2881/nepse-brings-data-api-real-time-data-within-30-seconds/">Paid Nepse API</a> which returned real-time data, but 10k-60k per month was too costly for a school student like me. </p>
<h3 id="nepse-changing-their-api">NEPSE changing their API</h3>
<p>This has been one of the biggest problems for me while making this API wrapper. Within a week of making this API wrapper, NEPSE did some breaking changes to their API. They changed the request method from <code>GET</code> to <code>POST</code> and added a payload of <code>id</code> is uniform across every request, but changes every time the <code>id</code> in response of <code>/market-open</code> endpoint changes. I created a <a target="_blank" href="https://docs.google.com/spreadsheets/d/1wKMa4ai4OcXmzuDCLlxtoxje_my6pfbz8i36XgTxSBY/edit?usp=sharing">mapping</a> of <code>\market-open</code>'s <code>id</code> to <code>id</code> sent in the payload of the <code>POST</code> request. But it didn't work out much because the numbers went up to 70 so it was not feasible to create a mapping for such huge numbers. I tried to figure out a mathematical relationship between those, but that didn't work as well. You can learn about the issue in detail <a target="_blank" href="https://github.com/Samrid-Pandit/nepse-api/issues/27">here</a>.</p>
<h1 id="conclusion">Conclusion</h1>
<p>All of this was a <strong>bitter-sweet</strong> experience. I learned a lot of new things, I learned about properly working with <code>asynchronous</code> code in python, creating <code>context managers</code>, <code>creating async generators</code>, <code>creating documentation</code>, <code>github actions</code>, and many more. I faced a ton of problems along the way, but those problems helped me grow even more towards being a better developer. In the end, I would just like to say, if you have any questions you can always DM in discord at <code>sussy#0002</code>, and it would be very helpful of you if you could contribute in 
<a target="_blank" href="https://github.com/Samrid-Pandit/nepse-api">nepse-api</a>.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/Samrid-Pandit/nepse-api">https://github.com/Samrid-Pandit/nepse-api</a></div>
]]></content:encoded></item></channel></rss>