[Tutor] pythonic

Albert-Jan Roskam sjeik_appie at hotmail.com
Wed Apr 4 15:34:18 EDT 2018


Op 2 apr. 2018 15:31 schreef Steven D'Aprano <steve at pearwood.info>:
>
> On Mon, Apr 02, 2018 at 06:49:52AM -0600, Mats Wichmann wrote:
> > On 04/02/2018 02:56 AM, Alan Gauld via Tutor wrote:
> > > On 02/04/18 04:19, Steven D'Aprano wrote:
> > >> On Sun, Apr 01, 2018 at 10:58:51PM +0100, Alan Gauld via Tutor wrote:
> > >>> On01/04/18 20:20, Albert-Jan Roskam wrote:
> > >>>> fmt="%Y-%m-%d %H:%M\n"
> > >>>> f.write(now.strftime(fmt))
> > >>>> Lately I've been using format(), which uses __format__, because I find it slightly more readable:
> > >>>> format(datetime.now(), "%Y-%m-%d %H:%M")
> > >>> Interesting,
> > >>> I didn't know that format() recognised the datetime format codes.
> > >> It doesn't. It is the datetime object that recognises them. format()
> > >> merely passes the format string to the datetime.__format__ method, which
> > >> is what recognises the codes. It doesn't care what it is.
> > > Aha! That makes sense. I've never really used format() so have never
> > > bothered to find out how it works. To the point that until this thread I
> > > hadn't realized we even had a __format__() operator.
> > >
> > > As I said, I need to do some reading. Obviously a gap in my python
> > > education.
> > >
> >
> > so since we're all learning things here, how would this play out with
> > the new f-strings?
>
> I don't think f-strings are even a bit Pythonic.

"There should be one-- and preferably only one --obvious way to do it.":
1-str.format
2-% interpolation
3-string.Template
4-f strings
-...

I think that at least a few of these methods should become deprecated. Maybe 2 and 3? (though I use 2 all the time!). Not sure about 4. A proper templating language like Jinja might be more desirable to have in the standard library, addition to a simple string substitution mechanism


More information about the Tutor mailing list