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

后端 未结 4 1595
北恋
北恋 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:26

    In the inspect module, currentframe is defined like this:

    if hasattr(sys, '_getframe'):
        currentframe = sys._getframe
    else:
        currentframe = lambda _=None: None
    

    So unless sys has a _getframe attribute, the interpolate function will not work.

    The docs for sys._getframe say:

    CPython implementation detail: This function should be used for internal and specialized purposes only. It is not guaranteed to exist in all implementations of Python.


    Writing

    "{x}, {y}, {z}".format(**vars())
    

    in the function body is not that much longer than

    interpolate("{x}, {y}, {z}")
    

    and your code will be more portable.

提交回复
热议问题