[Python-3000] Format specifier proposal

Andrew James Wade andrew.j.wade at gmail.com
Wed Aug 15 05:02:27 CEST 2007


On Tue, 14 Aug 2007 09:41:48 -0700
"Guido van Rossum" <guido at python.org> wrote:

> On 8/13/07, Andrew James Wade <andrew.j.wade at gmail.com> wrote:
> > On Mon, 13 Aug 2007 20:53:26 -0700
> > "Guido van Rossum" <guido at python.org> wrote:
> >
> > ...
> >
> > > One of my favorite examples of non-numeric types are the date, time
> > > and datetime types from the datetime module; here I propose that their
> > > __format__ be defined like this:
> > >
> > >   def __format__(self, spec):
> > >       return self.strftime(spec)
> >
> > You loose the ability to align the field then. What about:
> >
> >     def __format__(self, align_spec, spec="%Y-%m-%d %H:%M:%S"):
> >         return format(self.strftime(spec), align_spec)
> >
> > with
> >
> >     def format(value, spec):
> >         if "," in spec:
> >             align_spec, custom_spec = spec.split(",",1)
> >             return value.__format__(align_spec, custom_spec)
> >         else:
> >             return value.__format__(spec)
> >
> > ":,%Y-%m-%d" may be slightly more gross than ":%Y-%m-%d", but on the plus
> > side ":30" would mean the same thing across all types.
> 
> Sorry, I really don't like imposing *any* syntactic constraints on the
> spec apart from !r and !s.

Does this mean that {1!30:%Y-%m-%d} would be legal syntax, that __format__
can do what it pleases with? That'd be great: there's an obvious place
for putting standard fields, and another for putting custom formatting
where collisions with !r and !s are not a concern:
{1!30}
{1:%Y-%m-%d}
{1:!renewal date: %Y-%m-%d} # no special meaning for ! here.
{1!30:%Y-%m-%d}

"!" wouldn't necessarily have to be followed by standard codes, but I'm
not sure why you'd want to put anything else (aside from !r, !s) there.

> You can get the default format with a custom size by using !s:30.
>
> If you want a custom format *and* padding, just add extra spaces to the spec.

That doesn't work for ":%A" or ":%B"; not if you want to pad to a fixed
width. I really think you'll have support for the standard
string-formatting codes appear in most formatting specifications in some
guise or another; they may as well appear in a standard place too.

-- Andrew


More information about the Python-3000 mailing list