20

I have module foo, inside this module I dynamically created class:

def superClassCreator():
    return type("Bar", (object,), {})

Now, what I want to achieve is to make this new dynamic class visible as a class of this module:

import foo
dir(foo)
>>> [... 'Bar' ...]

Do you know how to do this?

0

1 Answer 1

24

You can use Bar = superClassCreator() in foo (at the module level).

Alternatively, from another module, you can add Bar as an attribute on foo:

import foo

foo.Bar = superClassCreator()

or, if the name must be taken from the generated class:

import foo

generatedClass = superClassCreator()
setattr(foo, generatedClass.__name__, generatedClass)

From within the foo module, you can set it directly on globals():

generatedClass = superClassCreator()
globals()[generatedClass.__name__] = generatedClass
del generatedClass

with an optional del statement to remove the generatedClass name from the namespace again.

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

10 Comments

What if the name is generated dynamically? You can't do this in that case.
When I print generatedClass.__module__ I see it's different then foo. Actually I would like to put it in that module and not in foo. Should I write setattr(generatedClass.__module__, generatedClass.__name__, generatedClass) in that case?
@mnowotka: That would not work, you'd need to look up the module in sys.modules. Use setattr(sys.modules[generatedClass.__module__], generatedClass.__name__, generatedClass). Note that __module__ is going to be the module in which superClassCreator() is defined.
@MartijnPieters - thats strange because it looks like generatedClass.__module__ is a module where the base class is defined. superClassCreator is defined in foo and as i said generatedClass.__module__ is different then that.
@mnowotka: you can set the __module__ attribute, btw. You can also provide a __module__ key in the dict argument to type(). So type('Bar', (object,), {'__module__': 'foo.baz'}). I've verified the C source of type(), it takes __name__ from the current globals. So it's your Django shell mucking about.
|

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.