I have a handful of objects that hold constant database values for the application, which look like something this:
class TestObject(object):
"""reflects constants in _test_object"""
_pairs = (
( 1 , 'A' ),
( 2 , 'B' ),
( 4 , 'C' ),
( 8 , 'D' ),
)
mapping = setup(_pairs)
The mapping
function creates a dict that gives me a k,v and v,k lookup based on the _pairs
. They're all in the form of "id,name".
In order to make things easier in the app, I often set the "text values" as an attribute as well:
class TestObject(object):
...
...
A = 1
B = 2
C = 4
D = 8
While this makes using the classes really great, it is a bit unwieldy to retype this all, and keep it in sync. Plus I have to write unit-tests to ensure the attributes match up with the right ids in the _pairs.
I've been trying to wrap my head around a way to skip writing this out, and just automatically populate each TestObject class with the attributes on the application startup.
I know I could override the class and have it check the _pairs/mapping attribute for a failover, but I'm really interested in whether or not it's even possible to programmatically populate the class as I need. There is no __class__
yet, because the class hasn't been defined yet.
just to be clear, the type of stuff i want to do is along the lines of this:
class NotValidPython():
_pairs = ((1,'A'),)
for (k,v) in _pairs:
setattr( __class__, v, k )