Python Forum

Full Version: passing a string to a function to be a f-string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i don't know how easy or hard this would be to do. i want to have a function that gets a sting from a caller and make it be like an f-string and do it it the context of the caller even though the caller does not have it as an f-string literal. it might be read from a file, for example. the str can have "{n}" in it and the n i gets is the caller's variable n. anyone know how to do this?
The following worked for me
n = 48

def func(fstring):
    n = 100
    return eval('f' + repr(fstring))

if __name__ == '__main__':
    result = func("There are {n} items")
    print(result)
Output:
There are 100 items
i want the caller's context. so, 48 would be expected.
It is very difficult because I'm typing with my cat on my knees but this works
import sys

n = 48

def eval_fstring(fstring, globals=None, locals=None):
    """Evaluate an fstring
    
    arguments:
        fstring: the fstring to evaluate
        globals, locals: same meaning as in the eval() function

    returns:
        the string evaluated
    """
    f = sys._getframe(1)
    try:
        if globals is None:
            globals = f.f_globals
        elif locals is None:
            locals = globals
        if locals is None:
            locals = f.f_locals
        return eval('f' + repr(fstring), globals, locals)
    finally:
        del f, globals, locals

def foo():
    result = eval_fstring("There are {n} items")
    print(result)

def bar():
    n = 300
    result = eval_fstring("There are {n} items")
    print(result)
    

if __name__ == '__main__':
    foo()
    bar()
Output:
There are 48 items There are 300 items