Python: is using “..%(var)s..” % locals() a good practice?

后端 未结 7 946
太阳男子
太阳男子 2020-11-27 13:02

I discovered this pattern (or anti-pattern) and I am very happy with it.

I feel it is very agile:

def example():
    age = ...
    name = ...
    pri         


        
相关标签:
7条回答
  • 2020-11-27 13:48

    The "%(name)s" % <dictionary> or even better, the "{name}".format(<parameters>) have the merit of

    • being more readable than "%0s"
    • being independent from the argument order
    • not compelling to use all the arguments in the string

    I would tend to favour the str.format(), since it should be the way to do that in Python 3 (as per PEP 3101), and is already available from 2.6. With locals() though, you would have to do this:

    print("hello {name} you are {age} years old".format(**locals()))
    
    0 讨论(0)
提交回复
热议问题