RickyWilson Wrote:will this produce accurate results?You can write a test,pytest is advisable.
Here also with a couple of 3.6 features,f-string and underscore numbers.
Added doc-string then
help()
will work.import math import pytest @pytest.mark.parametrize( 'size_bytes, expected', [ (1024 , '1.0 KB'), (1_048_576, '1.0 MB'), (1_099_511_627_776, '1.0 TB'), ] ) def test_convert_size(size_bytes, expected): '''Convert Bytes to Kilobytes,Megabytes,Gigabytes,Terabytes...''' if size_bytes == 0: return "0B" size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") i = int(math.floor(math.log(size_bytes, 1024))) power = math.pow(1024, i) size = round(size_bytes / power, 2) assert f"{size} {size_name}" == expectedpytest will find function named test and run values in
mark.parametrize()
Output:E:\1py_div\dec
λ pytest
============================= test session starts =============================
platform win32 -- Python 3.6.2, pytest-3.3.0, py-1.5.2, pluggy-0.6.0
rootdir: E:\1py_div\dec, inifile:
collected 3 items
byte_convert_test.py ... [100%]
========================== 3 passed in 0.12 seconds ===========================