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

Nat Goodspeed nat at lindenlab.com
Fri Sep 18 16:01:38 CEST 2015


On Thu, Sep 17, 2015 at 5:41 PM, Daniel Brake <danielthebrake at gmail.com> wrote:

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

What if you provide a __format__ function, as described in PEP 3101:
https://www.python.org/dev/peps/pep-3101/
(section "Controlling Formatting on a Per-Type Basis")?


More information about the Cplusplus-sig mailing list