feature_base.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. u"""
  2. Base classes for features that are backwards-incompatible.
  3. Usage:
  4. features = Features()
  5. features.add(Feature("py3k_feature", "power< 'py3k' any* >", "2.7"))
  6. PATTERN = features.PATTERN
  7. """
  8. pattern_unformatted = u"%s=%s" # name=pattern, for dict lookups
  9. message_unformatted = u"""
  10. %s is only supported in Python %s and above."""
  11. class Feature(object):
  12. u"""
  13. A feature has a name, a pattern, and a minimum version of Python 2.x
  14. required to use the feature (or 3.x if there is no backwards-compatible
  15. version of 2.x)
  16. """
  17. def __init__(self, name, PATTERN, version):
  18. self.name = name
  19. self._pattern = PATTERN
  20. self.version = version
  21. def message_text(self):
  22. u"""
  23. Format the above text with the name and minimum version required.
  24. """
  25. return message_unformatted % (self.name, self.version)
  26. class Features(set):
  27. u"""
  28. A set of features that generates a pattern for the features it contains.
  29. This set will act like a mapping in that we map names to patterns.
  30. """
  31. mapping = {}
  32. def update_mapping(self):
  33. u"""
  34. Called every time we care about the mapping of names to features.
  35. """
  36. self.mapping = dict([(f.name, f) for f in iter(self)])
  37. @property
  38. def PATTERN(self):
  39. u"""
  40. Uses the mapping of names to features to return a PATTERN suitable
  41. for using the lib2to3 patcomp.
  42. """
  43. self.update_mapping()
  44. return u" |\n".join([pattern_unformatted % (f.name, f._pattern) for f in iter(self)])
  45. def __getitem__(self, key):
  46. u"""
  47. Implement a simple mapping to get patterns from names.
  48. """
  49. return self.mapping[key]