Skip to content Skip to sidebar Skip to footer

How To Add A Dynamic Method Encoded In A String During Class Initialization?

I am developing an Agent class for an evolutionary algorithm. I need to add a method to it that is generated from a string inherited from the parents. Here a minimal example class

Solution 1:

This is because the Python compiler looks at all the l-values in a code block when determining which variables are local, and in this case, f is not defined as an l-value, so the compiler complains at compilation time rather than at run time. This is not an issue in REPL where every line is compiled separately.

You can instead use the locals() dict to access a variable name that is produced dynamically:

classAgent:
    def__init__(self, s='\tif x > y:\n\t\treturn 1'):
        self.f_template = f'def f(self, x,y):\n{s}'exec(self.f_template)
        self.f = partial(locals()['f'], self)

Post a Comment for "How To Add A Dynamic Method Encoded In A String During Class Initialization?"