[Tutor] pythonic
Mats Wichmann
mats at wichmann.us
Mon Apr 2 12:31:55 EDT 2018
On 04/02/2018 08:28 AM, Peter Otten wrote:
> Steven D'Aprano wrote:
>
>> On Mon, Apr 02, 2018 at 06:49:52AM -0600, Mats Wichmann wrote:
>
>>> 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.
>>
>> They look like string constants, but they're actually a hidden call to
>> eval().
>
> But because you cannot f-ify a string variable (without an additional eval()
> call) you aren't tempted to feed them user-provided data.
>
>> They can only be used once, and are not re-usable (unlike proper
>> templates):
>
> You can't eat your cake an have it. As "proper templates" they would indeed
> be as dangerous as eval().
>
>> By my count, they violate at least three of the Zen of Python:
>>
>> Explicit is better than implicit.
>> Simple is better than complex.
>> Special cases aren't special enough to break the rules.
>
> As I'm getting tired of writing
>
> "...{foo}...{bar}...".format(foo=foo, bar=bar, ...)
>
> lately I'd say they win big in the "practicality beats you-name-it" area.
so swooping back to the origial code, it seems there are several options
for expressing the output. Picking one of the lines (and replacing the
writes to a file with prints for simplicity):
print("Date: {}-{}-{} {}:{}\n".format(now.year,
now.month,
now.day,
now.hour,
now.minute))
print("Date:", format(now, "%Y-%m-%d %H:%M"))
print(f"Date: {now:%Y-%m-%d %H:%M}")
those aren't exactly identical, since the using %m-%d form causes
zero-padding:
Date: 2018-4-2 10:23
Date: 2018-04-02 10:23
Date: 2018-04-02 10:23
For me, I don't know if the f-string version is the most Pythonic, but
it has an appealing conciseness in this particular context :)
More information about the Tutor
mailing list