Using locals() and format() method for strings: are there any caveats?

前端 未结 3 1112
傲寒
傲寒 2020-12-29 01:04

Are there any disadvantages, caveats or bad practice warnings about using the following pattern?

def buildString(user, name = \'john\', age=22):
    userId =         


        
3条回答
  •  渐次进展
    2020-12-29 01:48

    If the format string is not user-supplied, this usage is okay.

    format is preferred over using the old % for string substitution.
    locals is built-in to Python and its behavior will be reliable.

    I think locals does exactly what you need.
    Just don't modify the dictionary from locals and I would say you have a pretty good solution.

    If the format string is user-supplied, you are susceptible to injection attacks of all sorts of badness.

提交回复
热议问题