- 1 year ago 125
Python Question

How to "inspect" custom types in sqlalchemy

I have a very simple

custom column/data type:

class ChoiceString(types.TypeDecorator):

impl = types.String

def __init__(self, choices, **kw):
self.choices = dict(choices)
super(ChoiceString, self).__init__(**kw)

def process_bind_param(self, value, dialect):
return [k for k, v in self.choices.iteritems() if v == value][0]

def process_result_value(self, value, dialect):
return self.choices[value]

And I am iterating over the table columns using a

from sqlalchemy.inspection import inspect

mapper = inspect(SomeTableClass)

for col in mapper.columns:
print col
# how to check the choice values?
print dir(mapper.columns[col]) # does not show the 'choices' attribute
print dir(inspect(mapper.columns[col])) # does not show the 'choices' attribute
print mapper.columns[col].choices # error

But I am can't seem to access the
custom attribute of the custom type. I also tried "inspecting" the column directly instead of the class, but that doesn't work either.

So how do we access custom attributes of custom types in sqlalchemy, while inspecting?

Answer Source

You're inspecting the Column objects, not their types. Access the type through the type attribute of a Column object:

In [9]: class SomeTableClass(Base):
   ...:     __tablename__ = 'sometableclass'
   ...:     id = Column(Integer, primary_key=True)
   ...:     choices = Column(ChoiceString({ 'asdf': 'qwer'}))

In [10]: mapper = inspect(SomeTableClass)

In [12]: mapper.columns['choices']
Out[12]: Column('choices', ChoiceString(), table=<sometableclass>)

In [13]: mapper.columns['choices'].type.choices
Out[13]: {'asdf': 'qwer'}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download