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

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

    A simpler and safer approach would be the code below. inspect.currentframe isn't available on all implementation of python so your code would break when it isn't. Under jython, ironpython, or pypy it might not be available because it seems to be a cpython thing. This makes your code less portable.

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

    this technique is actually described in the Python tutorial's Input and Output chapter

    This could also be done by passing the table as keyword arguments with the ‘**’ notation. This is particularly useful in combination with the new built-in vars() function, which returns a dictionary containing all local variables.

    also in the python docs for inspect.currentframe

    CPython implementation detail: This function relies on Python stack frame support in the interpreter, which isn’t guaranteed to exist in all implementations of Python. If running in an implementation without Python stack frame support this function returns None.

提交回复
热议问题