|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +from __future__ import unicode_literals |
| 4 | +from future.utils import python_2_unicode_compatible, string_types |
| 5 | + |
| 6 | +import uuid |
| 7 | + |
| 8 | + |
| 9 | +@python_2_unicode_compatible |
| 10 | +class Node(object): |
| 11 | + def __init__(self, identifier=None, auto_uuid=False): |
| 12 | + """ |
| 13 | + :param identifier: node identifier, must be unique per tree |
| 14 | + """ |
| 15 | + if not isinstance(identifier, string_types): |
| 16 | + raise ValueError( |
| 17 | + "Identifier must be a string type, provided type is <%s>" |
| 18 | + % type(identifier) |
| 19 | + ) |
| 20 | + if identifier is None: |
| 21 | + if not auto_uuid: |
| 22 | + raise ValueError("Required identifier") |
| 23 | + identifier = uuid.uuid4() |
| 24 | + self.identifier = identifier |
| 25 | + |
| 26 | + def line_repr(self, **kwargs): |
| 27 | + """Control how node is displayed in tree representation. |
| 28 | + """ |
| 29 | + return self.identifier |
| 30 | + |
| 31 | + def serialize(self, *args, **kwargs): |
| 32 | + return {"identifier": self.identifier} |
| 33 | + |
| 34 | + @classmethod |
| 35 | + def deserialize(cls, d, *args, **kwargs): |
| 36 | + if not isinstance(d, dict): |
| 37 | + raise ValueError("Deserialization requires a dict.") |
| 38 | + return cls._deserialize(d, *args, **kwargs) |
| 39 | + |
| 40 | + @classmethod |
| 41 | + def _deserialize(cls, d, *args, **kwargs): |
| 42 | + return cls(d.get("identifier")) |
| 43 | + |
| 44 | + def __str__(self): |
| 45 | + return "%s, id=%s" % (self.__class__.__name__, self.identifier) |
| 46 | + |
| 47 | + def __repr__(self): |
| 48 | + return self.__str__() |
0 commit comments