bitmath icon indicating copy to clipboard operation
bitmath copied to clipboard

Added __format__ method

Open jonathaneunice opened this issue 6 years ago • 6 comments

  • allows specifying precision in inline string formatting
  • e.g. 'size: {:0.1f}'.format(s)
  • using standard string formatting, not just bitmath.format
  • adds corresponding tests

Short description: Adds a format method to enable in-line string interpolation

If you have a bitmath object (of whatever unit), it's handy to be able to interpolate that value directly in a format string. E.g.:

size = bitmath.MiB(2.847598437)
print('size: {:.1f}'.format(size))

A__format__ method makes this possible. It's even neater in Python 3.6 and following, with its ability to automatically interpolate variables into strings.

size = bitmath.MiB(2.847598437)
print(f'size: {size:.1f}')

jonathaneunice avatar Jul 01 '18 22:07 jonathaneunice

The CI failures appear to be related to outdated configuration of the requirements, which I did not change, not test breakage.

jonathaneunice avatar Jul 01 '18 23:07 jonathaneunice

Using modern python3 versions (the 3.3 branch ended its official supported life on September 29, 2017), the tests pass.

jonathaneunice avatar Jul 03 '18 10:07 jonathaneunice

Thanks for the PR! I'll try to take a gander at this today. I'm excited about this one.

tbielawa avatar Jul 03 '18 15:07 tbielawa

I'd like this squashed down into a shorter number of commits if you can please. One or a couple, whichever makes more sense to you.

tbielawa avatar Jul 03 '18 15:07 tbielawa

@jonathaneunice this is a nice PR, do you still feel like trying to get this cleaned up and able to merge?

tbielawa avatar Aug 23 '18 15:08 tbielawa

It would be great to include this in bitmath. Especially with Python 3.6's f-strings.

byte_counts = [1, 1025, 1026*1024, 1027*1024*1024, 1028*1024*1024*1024]
for byte_count in byte_counts:
    size = bitmath.Byte(byte_count).best_prefix()
    print(f"{size.value:8.3f} {size.unit:>4}"))
1.000 Byte
1.001  KiB
1.002  MiB
1.003  GiB
1.004  TiB

florisla avatar Oct 15 '21 11:10 florisla