Skip to content

Commit 6decd18

Browse files
Merge pull request #34 from terrycojones/catch-index-error
Avert an IndexError when a totally non-numeric value is passed to EngNumber
2 parents a0ae760 + ac1e96f commit 6decd18

2 files changed

Lines changed: 15 additions & 3 deletions

File tree

engineering_notation/eng_notation.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22

33
from decimal import Decimal
44
import re
5-
from string import digits
6-
import sys
75
from types import NotImplementedType
86

97
from typing import Self
@@ -465,7 +463,8 @@ def __init__(
465463
466464
Raises:
467465
TypeError: If the value type is unsupported.
468-
ValueError: If a string value cannot be parsed by Decimal.
466+
ValueError: If a string value cannot be parsed by Decimal or has no
467+
numeric part.
469468
"""
470469
self.precision = 2 if precision is None else precision
471470
self._precision_explicit = precision is not None
@@ -474,6 +473,12 @@ def __init__(
474473

475474
if isinstance(value, str):
476475
numeric_part, _ = _split_value_and_unit(value)
476+
477+
if not numeric_part:
478+
# Raise a value error to avoid the IndexError that would otherwise
479+
# occur (due to numeric_part[-1]) if numeric_part is empty.
480+
raise ValueError(f"Value {value!r} has no numeric part.")
481+
477482
for suffix in _suffix_keys:
478483
if suffix == numeric_part[-1]:
479484
numeric_part = numeric_part[:-1] + _suffix_lookup[suffix]

tests/test_engnum.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -646,3 +646,10 @@ def test_to_float():
646646
# negative_numbers
647647
assert float(EngUnit("-220k")) == -220000.0
648648
assert float(EngUnit("-220m")) == -0.220
649+
650+
651+
def test_value_error():
652+
# Unconvertible values.
653+
654+
with pytest.raises(ValueError):
655+
EngUnit("XXX")

0 commit comments

Comments
 (0)