by anderskaseorg · 9y ago · 0 comments
You can write your own safe formatting engine in much less code.
def safe_format(fmt, **args):
return re.sub(r'\{([^{}]*)\}', lambda m: args.get(m.group(1)), fmt)
safe_format('{foo} {bar}', foo='Hello', bar='world') # Hello world
Add bells and whistles as desired.Of course, %s does the same thing (__str__) but at least %s doesn't take any arguments.
I'm not worried about executing arbitrary code, because it's not user-supplied and it's normal for a templating library to access attributes of objects you pass to it (if it was unsafe you shouldn't have done that). This is more of a snafu with the number of sensitive and powerful attributes available by default on Python objects.