Replace non-evaluable expressions by a placeholder in string formatting

You can do something like this using the __format__ method on a class that makes an effort to eval:

class Attempt:
     def __format__(self, evalstr):
        try:
            return str(eval(evalstr))
        except:
            return "<N/A>"

class A: ...

attempt = Attempt()
foo = A()

print(f"{attempt:1+2}")  # "3"
print(f"{attempt:foo.state}")  # "<N/A>"

foo.state = "valid"
print(f"{attempt:foo.state}")  # "valid"

Of course, this is only readable to someone who understands what attempt is. If this is just for attribute lookup, you could demand less of the reader by using the builtin getattr:

f"state={getattr(foo, 'state', '<N/A>')}"

This says clearly that the attribute may not exist, and if it doesn’t, <N/A> will be printed in place of its value.

1 Like