[Python-ideas] Briefer string format
Mike Miller
python-ideas at mgmiller.net
Mon Jul 20 02:53:12 CEST 2015
Hmm, I prefer this recipe sent to me directly by joejev:
>>> import sys
>>> from collections import ChainMap
>>> def f(cs):
... """Format a string with the local scope of the caller
...
... Parameters
... ----------
... cs : str
... The string to format.
...
... Returns
... -------
... formatted : str
... The string with the format units filled in.
... """
... frame = sys._getframe(1)
... return cs.format(**dict(ChainMap(frame.f_locals, frame.f_globals)))
...
>>> a = 1
>>> f('{a}')
'1'
For yours I'd use the "pile of poo" character: ;)
💩("{foo}", _())
Both of these might be slower and a bit more awkward than the f'' idea, though I
like them.
As to the original post, a pyflakes-type script might be able to look for name
errors to assuage concerns, but as I mentioned before I believe the task of
matching string/vars is still necessary.
-Mike
On 07/19/2015 04:59 PM, Paul Sokolovsky wrote:
> Hello,
>
> On Sun, 19 Jul 2015 16:35:01 -0700
> Mike Miller <python-ideas at mgmiller.net> wrote:
>
> []
>
>> csstext += f'{nl}{key}{space}{{{nl}'
>>
>> An "f-formatted" string could automatically format with the locals
>> dict. Not yet sure about globals, and unicode only suggested for
>> now.
>
> "Not sure" sounds convincing. Deal - let's keep being explicit rather
> than implicit. Brevity?
>
> def _(fmt, dict):
> return fmt.format(**dict)
> __ = globals()
> ___ = locals()
>
> foo = 42
>
> _("{foo}", __())
>
>
> If that's not terse enough, you can take Python3, and go thru Unicode
> planes looking for funky-looking letters, then you hopefully can reduce
> to
>
> .("{foo}", .())
>
> Where dots aren't dots, but funky-looking letters.
>
>
More information about the Python-ideas
mailing list