Skip to content

Commit

Permalink
Change the context setting of decimal to be local to the `get_int…
Browse files Browse the repository at this point in the history
…eger_digit` function, not global: #59

Signed-off-by: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
  • Loading branch information
thombashi committed Dec 31, 2024
1 parent 248c4be commit 412edd6
Showing 1 changed file with 18 additions and 14 deletions.
32 changes: 18 additions & 14 deletions dataproperty/_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,31 +10,35 @@
from typepy import Integer, RealNumber, TypeConversionError


decimal.setcontext(decimal.Context(prec=60, rounding=decimal.ROUND_HALF_DOWN))

_ansi_escape: Final = re.compile(r"(\x9b|\x1b\[)[0-?]*[ -\/]*[@-~]", re.IGNORECASE)


def get_integer_digit(value: Any) -> int:
float_type: Final = RealNumber(value)

try:
abs_value = abs(float_type.convert())
except TypeConversionError:
with decimal.localcontext() as ctx:
ctx.prec = 60
ctx.rounding = decimal.ROUND_HALF_DOWN

try:
abs_value = abs(Integer(value).convert())
abs_value = abs(float_type.convert())
except TypeConversionError:
raise ValueError(f"the value must be a number: value='{value}' type='{type(value)}'")
try:
abs_value = abs(Integer(value).convert())
except TypeConversionError:
raise ValueError(
f"the value must be a number: value='{value}' type='{type(value)}'"
)

return len(str(abs_value))
return len(str(abs_value))

if abs_value.is_zero():
return 1
if abs_value.is_zero():
return 1

try:
return len(str(abs_value.quantize(Decimal("1."), rounding=decimal.ROUND_DOWN)))
except decimal.InvalidOperation:
return len(str(abs_value))
try:
return len(str(abs_value.quantize(Decimal("1."), rounding=decimal.ROUND_DOWN)))
except decimal.InvalidOperation:
return len(str(abs_value))


class DigitCalculator:
Expand Down

0 comments on commit 412edd6

Please sign in to comment.