You get all of the columns from __table__.columns
:
That is true, but you should avoid accessing "protected" and "private" members of objects. Your linter should complain if you try to do this.
The proper way to access a tables columns is though SQLAlchemy's Runtime Inspection API. From the docs:
the return value of inspect() is guaranteed to obey a documented API, thus allowing third party tools which build on top of SQLAlchemy configurations to be constructed in a forwards-compatible way.
You can use it like this:
from sqlalchemy import inspect
# ###########################################
# Inspect a Mapped Ojbect
# https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#orm-mapper-inspection-mapper
# ###########################################
mapped_object = inspect(myTable)
mapped_object.columns.items()
[('col1',
Column('col1', Integer(), table=<myTable>, primary_key=True, nullable=False)),
('col2', Column('col2', Unicode(length=10), table=<myTable>)),
('col3', Column('col3', Integer(), table=<myTable>)),
('col4', Column('col4', Numeric(precision=10, scale=6), table=<myTable>)),
('col5', Column('col5', Numeric(precision=6, scale=3), table=<myTable>)),
('col6', Column('col6', Numeric(precision=6, scale=3), table=<myTable>))]
[column.key for column in mapped_object.columns]
['col1', 'col2', 'col3', 'col4', 'col5', 'col6']
# ###########################################
# Inspect a Mapped Instance
# https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#orm-mapper-inspection-instancestate
# ###########################################
my_table = myTable(...)
mapped_instance = inspect(my_table)
# Notice: This collection include 'child'. The columns from the mapped object did not.
mapped_instance.attrs.items()
[('child', <sqlalchemy.orm.state.AttributeState at 0xffff9c748130>),
('col1', <sqlalchemy.orm.state.AttributeState at 0xffff9c7481f0>),
('col2', <sqlalchemy.orm.state.AttributeState at 0xffff9c748190>),
('col3', <sqlalchemy.orm.state.AttributeState at 0xffff9c7482b0>),
('col4', <sqlalchemy.orm.state.AttributeState at 0xffff9c748100>),
('col5', <sqlalchemy.orm.state.AttributeState at 0xffff9c748160>),
('col6', <sqlalchemy.orm.state.AttributeState at 0xffff9c748370>)]
# Notice: You can get the same collection as the mapped object returned by going through the mapper.
mapped_instance.mapper.columns.items()
[('col1',
Column('col1', Integer(), table=<myTable>, primary_key=True, nullable=False)),
('col2', Column('col2', Unicode(length=10), table=<myTable>)),
('col3', Column('col3', Integer(), table=<myTable>)),
('col4', Column('col4', Numeric(precision=10, scale=6), table=<myTable>)),
('col5', Column('col5', Numeric(precision=6, scale=3), table=<myTable>)),
('col6', Column('col6', Numeric(precision=6, scale=3), table=<myTable>))]