4

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

3
  • Could you give a simple example, with some code and an explanation of what you're trying to achieve? Commented Oct 7, 2011 at 11:36
  • Thanks for clarifying. Now, what exactly do you mean by "I created dynamically a class A"? It sounds like it's not part of your .py file, nor do you generate the code as a string and eval it... so what it is that you do exactly? Commented Oct 7, 2011 at 11:51
  • Here is an example of what I wrote to create dynamically a class: Foo = type('Foo', (), {'bar':True}) Commented Oct 7, 2011 at 12:03

3 Answers 3

3

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

Yes it seems really hard. I will try to generate it by another way. Thx.
2

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

1 Comment

Thanks for your answer, but I think I was not clear in my post.
0

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

1 Comment

thanks but unfortunately, inspect.getsource does not work if you generate your class with type('A', () {'bar':True})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.