File tree Expand file tree Collapse file tree 2 files changed +10
-14
lines changed
Expand file tree Collapse file tree 2 files changed +10
-14
lines changed Original file line number Diff line number Diff line change 2525
2626
2727import math
28+ import re
2829import sys
2930
3031
@@ -328,23 +329,20 @@ class DataSize:
328329
329330 def __init__ (self , data ):
330331 try :
331- norm_size = data .strip ().lower ()
332- last = norm_size [- 1 ]
333- if last .isdigit ():
334- self ._value = int (norm_size )
335- self ._unit = "b"
336- elif last in self .MULTIPLIERS :
337- self ._value = int (norm_size [:- 1 ])
338- self ._unit = last
339- else :
332+ norm = str (data ).strip ().lower ()
333+ match = re .match (r"^(\d+(\.\d+)?)(?:\s*([bkmgt]))?$" , norm )
334+ if not match :
340335 raise ValueError
341336
342- if self ._value < 0 :
337+ self ._value = float (match .group (1 ))
338+ self ._unit = match .group (3 ) or "b"
339+
340+ if self ._unit not in self .MULTIPLIERS or self ._value < 0 :
343341 raise ValueError
344342
345343 except ValueError as exc :
346344 raise InvalidDataSize (
347- 'String not in size + unit format (i.e. " 10M", "100k", ...)'
345+ f"Invalid data size ' { data } '. Use formats like ' 10M', '2.5G', or '100'."
348346 ) from exc
349347
350348 @property
Original file line number Diff line number Diff line change @@ -128,9 +128,6 @@ def test_invalid(self):
128128 self .assertRaises (
129129 data_structures .InvalidDataSize , data_structures .DataSize , "-100t"
130130 )
131- self .assertRaises (
132- data_structures .InvalidDataSize , data_structures .DataSize , "0.5g"
133- )
134131 self .assertRaises (
135132 data_structures .InvalidDataSize , data_structures .DataSize , "10Mb"
136133 )
@@ -142,6 +139,7 @@ def test_value_and_type(self):
142139 def test_values (self ):
143140 self .assertEqual (data_structures .DataSize ("10m" ).b , 10485760 )
144141 self .assertEqual (data_structures .DataSize ("10M" ).b , 10485760 )
142+ self .assertEqual (data_structures .DataSize ("0.5g" ).b , 536870912 )
145143
146144
147145if __name__ == "__main__" :
You can’t perform that action at this time.
0 commit comments