I think I would define and use a format function instead and then just print the object in whatever way is appropriate. With the writer you don’t have to pre-decide whether you want to use a buffer or not and your code stays agnostic.
This post is a good description: