Monthly Archives: April 2017

Optional properties in JSON

I had to work with JSON data where many properties were optional. In other words, a dictionary at any level could have missing keys, and the corresponding value should be treated as missing. For example, for input data {"k1": {"k2": {"k3": 1}}}, a nested look-up of "k1", "m2", "n3" should result in a missing value.

The builtin dictionary get method would work if keys were only missing at the lowest level:

We couldn’t use if statement or try/except since most of the lookups occur inside expressions. The straightforward approach of checking for the presence of the key at each level is quite verbose:

Since values are known to be dictionaries, and empty dictionaries won’t have the key we’re looking up, we could improve it by using logical and short-circuit:

This is fine, if it only needs to be written in a couple of places. But if it’s a common theme for the data, this code is still unattractive and error-prone as it’s repeated over and over.

Replacing the dictionaries with defaultdict is no good: it would not work if nesting depth is not fixed and would add expensive noise to the object in the form of empty dictionaries with every lookup attempt.

We could flatten the JSON structure:

However, this means we can no longer pass around intermediate dictionaries and lists. If we only need the leaves and don’t mind the overhead of flattening each JSON object, it’s an acceptable solution.

A simpler solution that doesn’t torture the JSON structure and adds no overhead is to follow the example of unittest.mock.MagicMock that silently accepts every request without actually doing any real work:

For our immediate use case, we only need get and __getitem__ (for list index lookup), but I also added __getattr__ method for use below with member access. Also, we really only need a single instance of this class, but it’s safer to define __eq__: this way, we don’t have to worry about accidentally creating and comparing multiple instances.

If we want even more syntactic sugar, so we can write json_obj["k1"]["m2"]["n3"], we could convert all the dictionaries inside the json object to instances of a custom dict subclass. At this point, we’re really creating a mini-DSL, so we might as well allow attribute lookup in dictionaries: json_obj.k1.m2.n3:

This is a lot less intrusive than flattening the json structure, but it still adds a modest runtime overhead: both at the initial conversion and on subsequent lookups (only if the key is missing).

It wouldn’t be hard to return NA on non-existent indexes in lists, but if that’s the correct semantics in our domain, we probably should be using dictionaries instead of lists in the first place.

Update: a couple good solutions were suggested in response to this post on Reddit. One is:

I think it works best if there are no lists; with lists, the switching between {} and [] might become somewhat easy to mess up.

The other is to define a function that can be used like this: json_get(json_obj, "k1", "k2", "n3"). It’s good if every property is optional; it won’t be able to express that some properties are required, such as in json_obj.get("k1", NA)["m2"].get("m3", NA).

Python Type Annotation with Graph Algorithms. Part II (Classes)

Generic Class

In this part, we will implement graph data structure using classes and interfaces, and discuss when it’s worth overruling type hints.

We need to make a few design choices.

First, should we require the user to provide unique and hashable node objects, or should we accept any values and wrap them into class Node ourselves? Let’s do the safer thing and wrap values into Node instances: this protects us in case the values could become non-unique or non-hashable in the future.1

Second, should we store adjacency sets inside or outside Node? I have a slight personal preference for nodes knowing their adjacency information, since it occasionally allows us to use one function argument (a node) rather than two (a node and a graph).2

Third, should we separate Graph and Node interfaces from their implementation? For example, we can have abstract base classes IGraph and IMutableGraph from which all concrete implementations would inherit. Apart from making the design cleaner, it should help generate more precise type hints (e.g., a traversal function may work on any object that implements IGraph, since it doesn’t need to mutate anything). This is a good idea, but let’s do without interfaces for now; we’ll add them later.

Our first implementation looks like this:

A couple of minor type checking points:

  • Using None as default parameter value automatically adds Optional to the stated argument type.
  • We provided type hints for instance attributes in the class definition body of Node and Graph; this is a good practice, but it is also acceptable to annotate their types inside __init__ (or not at all if mypy can infer them)

Type System Limitations

Now, just like in Part I, let’s again add reverse adjacency information to Graph in order to make iteration through incoming edges faster. The new class ReversibleGraph should share a big part of its implementation with Graph, so it would make sense to derive it from Graph. We also want to reuse all of the global functions since they should work without change for both implementations.

However, if we follow this plan, our code will not type check. There are two reasons for that.

Liskov Substitution Principle

Python type hint system follows the so-called Liskov substitution principle, or LSP:

If X derives from Y, it should *always* be safe to substitute an instance of X in place of an instance of Y.3

Therefore, when mypy sees that ReversibleGraph inherits from Graph, it analyzes the code to see whether it is indeed safe to use a ReversibleGraph in place of Graph. It turns out that it’s not safe, and so the type check fails.

To see why it’s not always safe, consider this function:

If we try to call it with g of type ReversibleGraph and node of type Node, it would fail in runtime when the ReversibleGraph.remove_node tries to access the non-existent node.backward attribute.4

To summarize, mypy thinks inheritance is serious business, and that it represents a relationship with some strict guarantees (LSP). We, on the other hand, wanted to use inheritance just to help with code reuse. A feature is in the works that would let the programmer turn LSP on or off as desired; but for now, we have to find another solution.

We could satisfy mypy by using composition instead of inheritance (that is, by wrapping Graph instance inside ReversibleGraph instance). But let’s not do that because this will make the code less logical and more verbose. Instead, let’s simply mark the lines about which mypy complains with type: ignore. Those directives are very precise: they suppress error messages for that line, but the type checker still parses those lines, and uses information it learned from them to type check the rest of the program.

Types Outside the Type System

Since we were careful enough to make Graph and ReversibleGraph support the same API, a function like read_graph should work without change for both. However, its type annotation is not obvious.

The first argument can be any class that supports the mutable graph API, that is IGraphMutable. The return type should be based on the value of the first argument; for example, if we call read_graph(ReversibleGraph, ...), the type checker should conclude that the return type is ReversibleGraph. (We can’t set return type to IGraph since that would prevent us from using the reverse adjacency included in ReversibleGraph.)

If we write:

we can’t specify the return type.

Perhaps we can use a type variable to achieve the desired result:

This would have worked if IGraph wasn’t generic; unfortunately, type variables cannot be bound by a generic type5. We also cannot provide type arguments to type variables. The above code would not even pass mypy’s syntax check.

The problem is simple: the types we’ve been trying to define do not exist in mypy’s type system. Such types require more sophisticated language implementation and more learning effort to use, and they are usually found only in the more advanced functional languages (such as Haskell and Scala).

In my opinion, the best solution here is to make class Node non-generic by changing the type of its value attribute to Any6. This means we no longer need a generic class for Graph and Node, and so we can use type variable to provide type hints for graph functions. Now is the time to add the interface classes as we discussed earlier; it’s easier to do so without dealing with generics.

Our final implementation even reuses the test functions:




Note that we didn’t bother trying to prevent assignment to attributes in the immutable interfaces; for example, even though nodes of IGraph is an (immutable) AbstractSet, users can assign a new container to nodes. While @property could have insured against such accidental assignment, it’s probably not worth the runtime cost.7

Undirected Graphs

Our API for a directed graph is so limited that it fits an undirected graph as is; we can always separate out the interfaces later, when the need arises.

Conceptually, an undirected graph is equivalent to a directed graph that satisfies two constraints:

  • each edge has a corresponding edge in the opposite direction
  • there are no loops (i.e., edges with the same tail and head)

Therefore, one way to implement an undirected is to reuse our (directed) Graph implementation. We just need to modify the add_edge and remove_edge methods to ensure those constraints are never violated:

It might seem wasteful to store each edge twice. However, we can’t really improve on that. Let’s say we define order on nodes, and store each edge only once, in the adjacency set of the lower-valued node. In this case, iterating through neighbors would be ridiculously slow since neighbors may end up stored on any node.

Conclusion

Class-based representation keeps the API clean and stable.

However, as we make our approach more general, type hints become more complex, and at some point we run into the limitations of python type system.

By its nature, static type checking provides insurance against certain bugs at the cost of constraints on the developer. Very powerful type systems (such as in Scala, Haskell, Idris) are extremely flexible; but they are also slightly harder to learn, debug, and implement. Simpler type systems (e.g., in Java, C#, C++, and python) are less flexible, and will occasionally get in the way of the developers.

I don’t recommend non-trivial refactoring just to satisfy the type checker, unless it also improves code quality. Often, it’s better to just overrule mypy using:

  • type Any which is compatible with anything
  • # type: ignore comment which suppresses type checker errors in the current line
  • casts, which overrides the type that mypy inferred for a variable

Series Contents

Part I – Representing graphs as dictionaries or sets
Part II – Representing graphs as classes
Part III – Implementing graph traversal
Part IV – Trees and binary trees

Github with all the code