--
With the exception of serialising to disk in a safer format, I'd go with using a function. Having used (and been a fan of) Templates, it's very clean in readings dn writing to disk.
The safer option for any user input in my view is to use a dedicated library that escape mist things such as Jinja.
I saw your comment earlier about functions not being portable. As you are aware, everything in python is an object and as such a function can be pickled into a file and then unpicked and used. It has a security disadvantage because of that but in principle also a valid solution if you control the environment.