Pythonic Go code. The long arc of language convergence continues. With generics and iterators, Go is significantly closer to Python’s reusability and expressiveness. Take the built-in function sum . Prior to generics, a Go version would have needed separate implementations for int and float64 . But that was the least of the problems. Even with a Number interface, it also would have been restricted…
Contrarian view on cursor-based pagination. GraphQL documentation recommends cursor-based pagination , and it has subsequently become a popular standard. In general, we’ve found that cursor-based pagination is the most powerful of those designed. Especially if the cursors are opaque, either offset or ID-based pagination can be implemented using cursor-based pagination (by making the cursor the…
Companion guide to the Python packaging tutorial . This is not an overview of packaging , nor a history of the tooling . The intended audience is an author of a simple package who merely wants to publish it on the package index , without being forced to make uninformed choices. Build backends The crux of the poor user experience is choosing a build backend . The reader at this stage does not know…
There is no such thing as a “root field”. There is a common - seemingly universal - misconception that GraphQL root fields are somehow special, in both usage and implementation. The better conceptual model is that there are root types , and all types have fields. The difference is not just semantics; it leads to actual misunderstandings. Multiple queries A common beginner question is “can there be…
Contrarian view on composition over inheritance. The conventional wisdom is to prefer composition over inheritance . More specifically to use delegation over single inheritance. Like the recommendation on closing files , the advice is well-intentioned but omits the fact that Python does not support it well. Python has no mechanism for embedding or forwarding methods. And the despite its famous…
Decorators versus blocks and partial functions. Decorators are a beloved feature of Python, but like any good thing can be overused. The key is acknowledging that decorators are just functions . A function returning another function, usually applied as a function transformation using the @wrapper syntax. Common examples for decorators are classmethod() and staticmethod(). The decorator syntax is…
Litany against nulls. The myths and misconceptions regarding null behavior in GraphQL are epic. Even the spec is wrong. Inputs (such as field arguments), are always optional by default. However a non-null input type is required. In addition to not accepting the value null, it also does not accept omission. For the sake of simplicity nullable types are always optional and non-null types are always…
GraphQL resolvers should have been coroutines. This is how the GraphQL documentation introduces execution , as a hierarchy of resolvers: You can think of each field in a GraphQL query as a function or method of the previous type which returns the next type. In fact, this is exactly how GraphQL works. Each field on each type is backed by a function called the resolver which is provided by the…
Random selection utilities used to be common in interviews. Less so in Python circles because of the builtin random module. Still advanced examples may come up. First is a generalization of shuffle and sample . import itertools import random def shuffled(iterable): """Generate values in random order for any iterable. Faster than `random.shuffle` if not all values are required. More flexible than…
An old interview challenge is to generate prime numbers or check if a number is prime. No advanced mathematics needed, just variants on the Sieve of Eratosthenes . Starting with a basic prime checker. def isprime(n): divs = range ( 2 , int (n ** 0.5 ) + 1 ) return all (n % d for d in divs) % time isprime( 1_000_003 ) CPU times: user 83 µs, sys: 1e+03 ns, total: 84 µs Wall time: 85.1 µs True A…
How to solve the Hardest Logic Puzzle Ever programmatically. Three gods A, B, and C are called, in no particular order, True, False, and Random. True always speaks truly, False always speaks falsely, but whether Random speaks truly or falsely is a completely random matter. Your task is to determine the identities of A, B, and C by asking three yes-no questions; each question must be put to exactly…
GraphQL is the new ORM. REST and ORMs are both infamous for: over-fetching: fetching more data than is needed per request under-fetching: fetching less data than is needed, requiring multiple requests select N+1 problem: under-fetching applied to multiple associated objects GraphQL aims to overcome REST’s shortcomings through a flexible query language, and succeeds in doing so on the client side.…
Contrarian view on closing files. It has become conventional wisdom to always explicitly close file-like objects, via context managers. The google style guide is representative: Explicitly close files and sockets when done with them. Leaving files, sockets or other file-like objects open unnecessarily has many downsides, including: They may consume limited system resources, such as file…
Contrarian view on mutable default arguments. The use of mutable defaults is probably the most infamous Python gotcha. Default values are evaluated at definition time, which means mutating them will be persistent across multiple calls. Many articles on this topic even use the same append example. def append_to(element, to = []): to.append(element) return to append_to( 0 ) [0] append_to( 1 ) [0, 1]…
How to solve the water pouring puzzle programmatically. Given two jugs of capcity of 3 and 5 liters, acquire exactly 4 liters in a jug. Assume an unlimited water supply, and that jugs can only be filled or emptied, i.e., no estimations. First to model the data: a mapping of jug sizes to their current quantity. There are 3 primitive operations: filling a jug to capacity emptying a jug entirely…
How to solve the coin balance puzzle programmatically. Given a balance and a set of coins, which are all equal in weight except for one, determine which coin is of different weight in as few weighings as possible. Twelve-coin problem A more complex version has twelve coins, eleven or twelve of which are identical. If one is different, we don’t know whether it is heavier or lighter than the others.…
How to solve the Hat puzzle programmatically. Ten-Hat Variant In this variant there are 10 prisoners and 10 hats. Each prisoner is assigned a random hat, either red or blue, but the number of each color hat is not known to the prisoners. The prisoners will be lined up single file where each can see the hats in front of him but not behind. Starting with the prisoner in the back of the line and…
Split an iterable into equal sized chunks. A common task and interview question, with many variants. It’s frequently asked and answered in a way that’s suboptimal and only handles one specific case . The goal here is to present definitive, general, and efficient solutions. The first variant is whether or not the chunks will overlap. Although this could be generalized into a step parameter, it’s…
A Paul Graham classic , the accumulator function. As an illustration of what I mean about the relative power of programming languages, consider the following problem. We want to write a function that generates accumulators– a function that takes a number n, and returns a function that takes another number i and returns n incremented by i. (That’s incremented by, not plus. An accumulator has to…
Contrarian view on map and filter . Although PEP 8 is silent on the topic, it’s become recommended in many Python circles to eschew map and filter in favor of generator expressions or list comprehensions. For example, this Stack Overflow question received and accepted a typical response. Ironically, that question misquoted the google style guide , which this author happens to agree with. Use list…