2
\$\begingroup\$

There are two aspects to this question that are inter-related.

  1. Change I've made to the trie module in python (PyPI, GitHub) to make it serialisable (and deserialisable).

The change I made is visible on GitHub. I added two functions to the Node class used in serialisation.

def __getstate__(self):
    return (self.parent, self.key, self.nodes, self.value)

def __setstate__(self, state):
    (self.parent, self.key, self.nodes, self.value) = state
    if type(self.value) == object:
        self.value = Node.no_value

The Node class uses an instance of object to signify that there is no value for that Node. If you serialise and deserialise a Trie of Nodes then the values are set to different instances of object, this is why I added a check for the type being object and replacing it with Node.no_value.

Is this a reasonable way of doing things? Is anyone likely to want to store an actual instance of object?

  1. Is there a better way of signifying that a Node has no value, that is more robust to serialisation?
\$\endgroup\$
1
\$\begingroup\$

Use None rather then Node.no_value.

None is the typical value to use for the absence of value. However, its possible that you actually want to store None in your trie, so that doesn't work.

Checking the type of the object is not really a good plan because somebody could decide to store plain objects in your trie. I would add another value, a boolean "self.value is Node.no_value", to the tuple in setstate. By checking that I could be sure that it works correctly.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.