bignum.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #
  2. # Licensed to the Apache Software Foundation (ASF) under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. The ASF licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing,
  13. # software distributed under the License is distributed on an
  14. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. # KIND, either express or implied. See the License for the
  16. # specific language governing permissions and limitations
  17. # under the License.
  18. from __future__ import annotations
  19. from typing import TYPE_CHECKING
  20. from airflow.utils.module_loading import qualname
  21. if TYPE_CHECKING:
  22. import decimal
  23. from airflow.serialization.serde import U
  24. serializers = ["decimal.Decimal"]
  25. deserializers = serializers
  26. __version__ = 1
  27. def serialize(o: object) -> tuple[U, str, int, bool]:
  28. from decimal import Decimal
  29. if not isinstance(o, Decimal):
  30. return "", "", 0, False
  31. name = qualname(o)
  32. _, _, exponent = o.as_tuple()
  33. if isinstance(exponent, int) and exponent >= 0: # No digits after the decimal point.
  34. return int(o), name, __version__, True
  35. # Technically lossy due to floating point errors, but the best we
  36. # can do without implementing a custom encode function.
  37. return float(o), name, __version__, True
  38. def deserialize(classname: str, version: int, data: object) -> decimal.Decimal:
  39. from decimal import Decimal
  40. if version > __version__:
  41. raise TypeError(f"serialized {version} of {classname} > {__version__}")
  42. if classname != qualname(Decimal):
  43. raise TypeError(f"{classname} != {qualname(Decimal)}")
  44. return Decimal(str(data))