开发者

Generate python code of a class from an python instance of this class

开发者 https://www.devze.com 2023-04-11 23:13 出处:网络
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.

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 help开发者_运维技巧s 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:

kwargs = {answer=42, name='foo'}

import class_maker
SomeClass1 = class_maker.make_class(**kwargs)

The other option is generate the Python code you want directly, exec it to make the class, and then save it with the class.

code = '''class MyClass:
    pass
'''

the_locals = {}
exec(code, globals(), the_locals)
MyClass = the_locals['MyClass']
MyClass._code = code

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 using exec. (But even the Python standard library uses it for dynamic classes sometimes.)


You can use compile(), exec() or eval() depending on your exact needs.


Perhaps you could use inspect.getsource:

import inspect

def generate_kls_A(num):
    class A(object):
        def __init__(self):
            self.init = num
    return A
kls_A=generate_kls_A(1)
print(inspect.getsource(kls_A))

yields:

class A(object):
    def __init__(self):
        self.init = num
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号