0

I have a format string fmt on which the format method will be called in another module which I have no control over.

In this format string I want to optionally include a field if it was provided as an argument to the format method, otherwise I want to leave it out.

Something like:

fmt = 'Optional value: {value if wasPassed("value") else ""}'
fmt.format(value = "foo") #Should return 'Optional value: foo'
fmt.format() #Should return 'Optional value: ' and not throw a Key error

Since I don't have access to the "format" call I want to solve this within the string somehow. For context I am using this as a format string passed to the logging module but I would really like a general solution for the above problem.

In the specific use case I could pass a custom formatter to the logger but this question really aims at the problem of solving this within an expression in the string to be formatted. (If that is just impossible I would also appreciate an answer indicating why, so that I can stop barking up the wrong tree and just use a custom formatter)

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Chris
  • 445
  • 6
  • 11
  • Does this answer your question? [Leaving values blank if not passed in str.format](https://stackoverflow.com/questions/19799609/leaving-values-blank-if-not-passed-in-str-format) – Gabio Apr 24 '20 at 09:16
  • Since I dont have access to the client code I cant really change from `format` to `format_map`. In my specific case I might be able to work around it by specifying a custom formatter to the logger but it does not answer the question of wether / how it would be possible to solve this just within an expression in the formatted string. – Chris Apr 24 '20 at 09:26

1 Answers1

-1

Assuming you have control over when the module uses the argument, you could write a 'wrapping' function e.g.

def myformat(fmt, arg=""):
    module.method(fmt, arg)

Alternatively something like the recursive method here (based on catching and handling the KeyError) might be all that's possible (based on docs), as you don't have access to the method internals: https://stackoverflow.com/a/56895928/7224691

Though I'd be careful on using this method, especially as it won't be applicable to more complicated module methods, which could cause side effects on the next iteration (or just simply print a string twice instead of once).

The above is intended as a general answer, whereas for a specific answer on the logging aspect of this question, we would likely (assuming no other possible method) need to know what module you are using.

Ben
  • 138
  • 2
  • 9