Skip to content

Simple precision control #64

Open
Open

Description

@timlnx

From @kapsh in #61

What do you think about adding precision argument to best_prefix method as shortcut for most commonly required operation?

This is a good idea. I also find the method for controlling precision rather verbose

As a bitmath user I want a simple way to control precision printing so that I don't have to use extra verbose syntax

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.

Activity

  1. self-assigned this
    on Mar 16, 2018
  2. kapsh commented on Mar 16, 2018

    @kapsh
    Contributor

    @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.

  3. timlnx commented on Mar 17, 2018

    @timlnx
    OwnerAuthor

    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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions