Skip to content Skip to sidebar Skip to footer

Dynamic Python Class Definition In Sqlalchemy

I'm creating a backend application with SQLAlchemy using the declarative base. The ORM requires about 15 tables each of which maps to a class object in SQLAlchemy. Because these cl

Solution 1:

This sounds like a sketchy idea. But it's fun to solve so here is how you make it work.

As I understand it, your problem is you want to add dynamically created classes to a module. I created a hack using a module and the init.py file.

dynamicModule/__init__.py:

importdynamic

class_names = ["One", "Two", "Three"]

for new_name in class_names:
     dynamic.__dict__['Class%s' % new_name] = type("Class%s" % (new_name), (object,), {'attribute_one': 'blah'})

dynamicModule/dynamic.py:

"""Empty file"""

test.py:

import dynamicModule
from dynamicModule import dynamic
from dynamicModule.dynamic import ClassOne

dynamic.ClassOne
"""This all seems evil but it works for me on python 2.6.5"""

__init__.py:

"""Empty file"""

Solution 2:

[Note, this is the original poster]

So after some thinking and talking to people I've decided that that ability to dynamically create and assign variables to class objects in the global name space in this way this just isn't something Python supports (and likely with good reason). Even though I think my use case isn't too crazy (pumping out predefined list of identically constructed classes) it's just not supported.

There are lots of questions that point towards using a dictionary in a case like this, such as this one: https://stackoverflow.com/a/10963883/1216837. I thought of something like that but the issue is that I need those classes in the module name space so I can import them into other modules. However, adding them with globals() like globals()['MyClass'] = class_dict['MyClass'] seems like it's getting pretty out there and my impression is people on SO frown on using globals() like this.

There are hacks such as the one suggested by patjenk but at a certain point the obfuscation and complexity out weight the benefits of the clarity of declaring each class object statically. So while it seems repetitive I'm just going to write out all the class definitions. Really, this end up being pretty concise/maintainable:

Class1 = class_factory('class1')
Class2 = class_factory('class2')
...

Post a Comment for "Dynamic Python Class Definition In Sqlalchemy"