In my code, I generate new python classes at runtime. For some of them, I want to generate the python code, just as if I wrote these classes in a .py file.
Let’s say that I created dynamically a class A:
type('A', (), {'bar':True} which is equivalent to the code:
class A(object):
bar=True
What I want is to generate this equivalent code from my dynamic class.
I’m trying to implement a function “generate_A_code”
kls_A = type('A', (), {'bar':True}
kls_A.generate_A_code()
Hope this helps a bit.
Thanks
Generating the Python code from the class object itself is practically impossible. You need to save the instructions for generating the class in another way.
The best way may be having a function to make the class, and importing & calling it in the generated code. So the generated code would look like this:
The other option is generate the Python code you want directly,
execit to make the class, and then save it with the class.As always with
exec, be very careful using it. It can run any Python code. Think hard if there’s any way to do whatever you need to do in a different way. People will shout at you for usingexec. (But even the Python standard library uses it for dynamic classes sometimes.)