[Python-ideas] Short form for keyword arguments and dicts
MRAB
python at mrabarnett.plus.com
Mon Jun 24 17:55:36 CEST 2013
On 24/06/2013 16:40, Barry Warsaw wrote:
> On Jun 22, 2013, at 12:27 PM, Anders Hovmöller wrote:
>
>>Keyword arguments are great for increasing readability and making code more
>>robust but in my opinion they are underused compared to the gains they can
>>provide. You often end up with code like:
>>
>>foo(bar=bar, baz=baz, foobaz=foobaz)
>
> The DRY motivation for this proposal reminds me of PEP 292 ($-strings) and
> flufl.i18n. In some of the earlier i18n work I did, the repetition was
> overwhelmingly inconvenient. Generally, it doesn't bother me, but I really
> hated doing things like:
>
> real_name = get_real_name()
> email_address = get_email_address()
> message = _('Hi $real_name <$email_address>').safe_substitute(
> real_name=real_name, email_address=email_address)
>
> not to mention the high probability of typos, and the added noise making the
> source harder to read. flufl.i18n then, shortens this to:
>
> real_name = get_real_name()
> email_address = get_email_address()
> message = _('Hi $real_name <$email_address>')
>
> The locals and globals are collected into the substitution dictionary, to be
> applied after the source string is translated.
>
> Yes, the implementation uses the dreaded sys._getframe(), but it's worth it.
>
> http://tinyurl.com/kqy3hbz
> http://tinyurl.com/lalxjaf
>
Do you have to use sys._getframe()?
Although it's a little longer:
def _(message, variables):
return re.sub(r"\$(\w+)", lambda m: variables[m.group(1)], message)
You can then do this:
>>> real_name = "REAL NAME"
>>> email_address = "EMAIL ADDRESS"
>>> _(m, globals())
'Hi REAL NAME <EMAIL ADDRESS>'
>>> _(m, locals())
'Hi REAL NAME <EMAIL ADDRESS>'
>>> def test():
real_name = "LOCAL REAL NAME"
email_address = "LOCAL EMAIL ADDRESS"
print(_(m, locals()))
More information about the Python-ideas
mailing list