user466130
user466130

Reputation: 367

way to create fstring inside a fstring

is it possible to create a fstring inside a fstring?

what i am trying now is to create a dynamic function using eval.

my code is something like this

func_string = ''
for scenario in ['scene1', 'scene2']:
    for aa in ['int', 'ext']:
         func_string += f'''
             def function_{scenario}_{aa}(part):
                 print(f"this is {part}")
           '''


eval(func_string)
function_scene1_int('part1')

running this script will return: this is part1

Upvotes: 0

Views: 189

Answers (1)

joel
joel

Reputation: 7867

You can make a factory method like this ...

def factory(a, b):
    def g(c):
        print(f'this is {c}')
        return f'other stuff using {a}, {b} and {c}'  # if you want to
    return g

then use it like

>>> f = factory('scene1', 'int')
>>> msg = f('part1')
this is part1
>>> print(msg)
other stuff using scene1, int and part1

Upvotes: 1

Related Questions