token.py 854 B

123456789101112131415161718192021222324252627282930
  1. from __future__ import unicode_literals
  2. from builtins import str
  3. import six
  4. @six.python_2_unicode_compatible
  5. class Token:
  6. def __init__(self, string="", metadata=None):
  7. self.string = string
  8. self.metadata = metadata or {}
  9. def __str__(self):
  10. return self.string
  11. def __repr__(self):
  12. return '<Token "{}">'.format(str(self))
  13. def update(self, fn):
  14. """A token update function is used when updating or optionally
  15. when cloning a token."""
  16. # TODO: we require functions to have two parameters, JS doesn't care
  17. self.string = fn(self.string, self.metadata)
  18. return self
  19. def clone(self, fn=None):
  20. """Applies the given function to the wrapped string token."""
  21. fn = fn or (lambda s, m: s)
  22. return Token(fn(self.string, self.metadata), self.metadata)