Skip to content

Commit 25dadab

Browse files
committed
Improve types and comments
1 parent b60b317 commit 25dadab

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

qrcode/image/svg.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,21 +42,29 @@ def units(self, pixels: int | Decimal, text: Literal[False]) -> Decimal: ...
4242
@overload
4343
def units(self, pixels: int | Decimal, text: Literal[True] = True) -> str: ...
4444

45-
def units(self, pixels, text=True):
45+
def units(self, pixels: int, text=True) -> Decimal | str:
4646
"""
47-
Returns pixel values directly.
47+
Converts pixel values into a decimal representation with up to three decimal
48+
places of precision or a string representation, optionally rounding to
49+
lower precision without data loss.
4850
"""
4951
units = Decimal(pixels)
5052
if not text:
5153
return units
54+
55+
# Round the decimal to 3 decimal places first, then try to reduce precision
56+
# further by attempting to round to 2 decimals, 1 decimal, and whole numbers.
57+
# If any rounding causes data loss (raises Inexact), keep the previous
58+
# precision.
5259
units = units.quantize(Decimal("0.001"))
5360
context = decimal.Context(traps=[decimal.Inexact])
5461
try:
5562
for d in (Decimal("0.01"), Decimal("0.1"), Decimal(0)):
5663
units = units.quantize(d, context=context)
5764
except decimal.Inexact:
5865
pass
59-
return f"{units}"
66+
67+
return str(units)
6068

6169
def save(self, stream, kind=None):
6270
self.check_kind(kind=kind)

0 commit comments

Comments
 (0)