utils.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """The module contains miscellaneous helpers.
  2. It's not considered part of the public ufoLib API.
  3. """
  4. import warnings
  5. import functools
  6. numberTypes = (int, float)
  7. def deprecated(msg=""):
  8. """Decorator factory to mark functions as deprecated with given message.
  9. >>> @deprecated("Enough!")
  10. ... def some_function():
  11. ... "I just print 'hello world'."
  12. ... print("hello world")
  13. >>> some_function()
  14. hello world
  15. >>> some_function.__doc__ == "I just print 'hello world'."
  16. True
  17. """
  18. def deprecated_decorator(func):
  19. @functools.wraps(func)
  20. def wrapper(*args, **kwargs):
  21. warnings.warn(
  22. f"{func.__name__} function is a deprecated. {msg}",
  23. category=DeprecationWarning,
  24. stacklevel=2,
  25. )
  26. return func(*args, **kwargs)
  27. return wrapper
  28. return deprecated_decorator
  29. # To be mixed with enum.Enum in UFOFormatVersion and GLIFFormatVersion
  30. class _VersionTupleEnumMixin:
  31. @property
  32. def major(self):
  33. return self.value[0]
  34. @property
  35. def minor(self):
  36. return self.value[1]
  37. @classmethod
  38. def _missing_(cls, value):
  39. # allow to initialize a version enum from a single (major) integer
  40. if isinstance(value, int):
  41. return cls((value, 0))
  42. # or from None to obtain the current default version
  43. if value is None:
  44. return cls.default()
  45. return super()._missing_(value)
  46. def __str__(self):
  47. return f"{self.major}.{self.minor}"
  48. @classmethod
  49. def default(cls):
  50. # get the latest defined version (i.e. the max of all versions)
  51. return max(cls.__members__.values())
  52. @classmethod
  53. def supported_versions(cls):
  54. return frozenset(cls.__members__.values())
  55. if __name__ == "__main__":
  56. import doctest
  57. doctest.testmod()