Is a string formatter that pulls variables from its calling scope bad practice?

后端 未结 4 1594
北恋
北恋 2020-11-30 14:04

I have some code that does an awful lot of string formatting, Often, I end up with code along the lines of:

\"...\".format(x=x, y=y, z=z, foo=foo, ...)
         


        
4条回答
  •  心在旅途
    2020-11-30 14:39

    The good old mailman has a function _ that does exactly this thing:

    def _(s):
        if s == '':
            return s
        assert s
        # Do translation of the given string into the current language, and do
        # Ping-string interpolation into the resulting string.
        #
        # This lets you write something like:
        #
        #     now = time.ctime(time.time())
        #     print _('The current time is: %(now)s')
        #
        # and have it Just Work.  Note that the lookup order for keys in the
        # original string is 1) locals dictionary, 2) globals dictionary.
        #
        # First, get the frame of the caller
        frame = sys._getframe(1)
        # A `safe' dictionary is used so we won't get an exception if there's a
        # missing key in the dictionary.
        dict = SafeDict(frame.f_globals.copy())
        dict.update(frame.f_locals)
        # Translate the string, then interpolate into it.
        return _translation.gettext(s) % dict
    

    So if Barry Warsaw can do that, why can't we?

提交回复
热议问题