_f_lookup = { "some arbitrary f-string {foo} {bar} {g}": "translated {bar} {g!r} {foo}", "school {school}": "escuela {school}", } _f_cache = {} def _f(s): # Find the translated string. translated = _f_lookup[s] # See if we're already compiled this. result = _f_cache.get(translated) if result is not None: return result # Convert to an f-string, then compile it, cache it, and return it. c = compile(f"f{translated!r}", filename=translated, mode="eval") _f_cache[translated] = c return c # Some function that contains an "f-string" that needs translating. def fn(foo): bar = 100 return eval(_f("some arbitrary f-string {foo} {bar} {g}")) g = "a global" print(fn(200)) g = 3.1415 print(fn(300))