Open tbielawa opened 6 years ago
@tbielawa thanks for feedback.
I already took a look into the code and found that best_prefix
actually returns instance of suitable subclass of Bitmath
. In this case it would be awkward to pass precision argument to the constructor.
Next suggestion then. With custom __format__
magic method bitmath objects could partially understand format mini-language (like datetime objects). So I assume the usage example as:
>>> size = bitmath.Byte(314159265)
>>> size.best_prefix()
MiB(299.60562229156494)
>>> 'Size is {0:.2}'.format(size.best_prefix())
Size is 299.61 MiB
It looks quite pythonic IMO.
I see what you're going for. I didn't realize before that there is a magic __format__
method. I'm going to look at that closer.
In the mean time, consider the following work-around as well: adjusting the default format string. As noted in the docs, each instance can already be formatted directory using the format
method:
In [15]: ex = bitmath.MiB(10.0/3.0)
In [16]: print(ex)
3.33333333333 MiB
In [17]: print(ex.format('{value:0.2f} {unit}'))
3.33 MiB
However, if you want 2-digit precision by default, you can simply change the default formatting string:
In [1]: import bitmath
In [2]: bitmath.format_string = '{value:0.2f} {unit}'
In [3]: ex = bitmath.MiB(10.0/3.0)
In [4]: print(ex)
3.33 MiB
In [5]: print(ex.format('{value:0.2f} {unit}'))
3.33 MiB
From @kapsh in #61
This is a good idea. I also find the method for controlling precision rather verbose
It's a fairly open definition at the moment, one which needs refinement. I think the idea is a very solid one though and I bet there are a lot of people who would find value in this.