[C++-sig] formatting str of exposed type

Stefan Seefeld stefan at seefeld.name
Fri Sep 18 16:15:07 CEST 2015


On 09/17/2015 05:41 PM, Daniel Brake wrote:
>
> Hi Boost Python,
>
> I would like a C++ class which I am exposing through
> Boost.Python (initially,the boost::multiprecision::mpfr_float, with
> expression templates turned off  --  eventually a whole pile of types
> depending on mpfr_float) to be able to respond to the %precision n
> command, for example, from ipython.  Additionally, I would like to be
> able to use a format spec such as
>
> print('{0:.40}'.format(b))
>
> to print a variable b with 40 digits of precision.  Even better, I
> would like to be able to put a standard formatting letter in the
> format string preceding the .format call. 
>
> My best guess would be to def("format",...) as a free function for my
> class_, but I also guess that this is a standard operation, and I
> would rather use a standard solution.  Parsing the formatting string
> myself doesn't sound like much fun, and am hoping for a little insight
> from the mailing list. 
>

Note that in the invocation above, 'format' is a method of 'str', not
the type that's being formatted. Thus, if b is an instance of your
mpfr_float, you don't have to re-implement 'format'.

What I'd rather do is provide a "__str__" member function (you could use
the standard mechanism involving the "str(self)" syntax from
Boost.Python) that just invokes the above. Depending on how flexible you
want this to be, you could hard-code the formatting spec into your
wrapper class, or add a 'format' attribute that's being used, and which
could then be customized from within Python. The possibilities are
endless...

    Stefan

-- 

      ...ich hab' noch einen Koffer in Berlin...



More information about the Cplusplus-sig mailing list