I often write the following code:
print('object', 'moved', 'from =', object.location, 'dest =', new_location)
print('object', 'created', 'at =', object.location, 'status =', status)
and so on.
I was planning to replace all of these with a function log:
def log(self, action, **details):
print('object', action, end = '')
for var, value in state.items():
print(var, '=', value, end = '')
print()
This almost works – except for two problems. First, I can’t control the order of the output, and it’s important to me. Of course, details is just a dictionary, so the order of the parameters is lost. Second, I can’t use any language keywords, e.g., from as the name of the keyword argument.
Is there any solution that avoid unnecessary verbosity but doesn’t suffer from these problems?
The reason I want to use log function is that I may want to disable / enable it or change the format in a single location.
You know about the logging module, I take it?
I would just use preformed messages, and substitute the necessary bits in:
You might prefer the new style of string formatting:
If you did need to do it with a dictionary-like structure, you could make an OrderedDict. But that is a bit more verbose. And it’s not really the “one obvious way to do it”.