fork download
  1. import string
  2.  
  3.  
  4. class FormatPlaceholder:
  5. def __init__(self, key):
  6. self.key = key
  7. def __format__(self, spec):
  8. result = self.key
  9. if spec:
  10. result += ":" + spec
  11. return "{" + result + "}"
  12. def __getitem__(self, index):
  13. self.key = "{}[{}]".format(self.key, index)
  14. return self
  15. def __getattr__(self, attr):
  16. self.key = "{}.{}".format(self.key, attr)
  17. return self
  18.  
  19.  
  20. class FormatDict(dict):
  21. def __missing__(self, key):
  22. return FormatPlaceholder(key)
  23.  
  24.  
  25. def safe_format_alt(text, source):
  26. formatter = string.Formatter()
  27. return formatter.vformat(text, (), FormatDict(source))
  28.  
  29. print(safe_format_alt("{a[0].x[2]}", {}))
Success #stdin #stdout 0.02s 9508KB
stdin
Standard input is empty
stdout
{a[0].x[2]}