1

I'm defining a few classes dynamically using type() and placing them in a list as I do so. I would, however, like to make the classes available from the module. That, for example, I can call from factories import PersonFactory if my module is factories.py and a dynamic class I create is PersonFactory.

This is a portion of the code in factories.py:

factories = []

for name, obj in models:
    factory_name = name + 'Factory' # e.g. PersonFactory
    attrs = assemble_factory_attrs(obj, factory_name)
    f = type(factory_name, (object,), attrs)
    factories.append(f)

# I wanted to "release" the classes into the module definition through `*factories`
# but I get this syntax error: "SyntaxError: can use starred expression only as assignment target"
*factories

Thank you!

aralar
  • 3,022
  • 7
  • 29
  • 44
  • http://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-in-python-via-a-while-loop – Jayanth Koushik Jun 22 '15 at 17:48
  • python treats `*factories` as an assignment; you can use `exec('%s = type(factory_name, (object,), attrs)' % factory_name)` instead – LittleQ Jun 22 '15 at 17:56

1 Answers1

1

You can add them to the modules globals() -- it will look something like this:

factories = []
module = globals()

for name, obj in models:
    factory_name = name + 'Factory' # e.g. PersonFactory
    attrs = assemble_factory_attrs(obj, factory_name)
    f = type(factory_name, (object,), attrs)
    module[factory_name] = f
    factories.append(f)

Now they are both at the module (global) scope, and in the list factories.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237