Understanding MetaData() from SQLAlchemy in Python

Viewed 15873

I am trying to understand what the MetaData() created object is in essence. It is used when reflecting and creating databases in Python (using SQLAlchemy package).

Consider the following working code:

/ with preloaded Engine(sqlite:///chapter5.sqlite) and metadata = MetaData(): when I call metadata in the console, it returns 'MetaData(bind=None)' /

# Import Table, Column, String, and Integer
from sqlalchemy import Table, Column, String, Integer

# Build a census table: census
census = Table('census', metadata,
               Column('state', String(30)),
               Column('sex', String(1)),
               Column('age', Integer()),
               Column('pop2000', Integer()),
               Column('pop2008',Integer()))

# Create the table in the database
metadata.create_all(engine)

Of course by typing type(metadata) I get exactly what type of object metadata is: sqlalchemy.sql.schema.MetaData. In SQLAlchemy documentation it is written

MetaData is a container object that keeps together many different features of a database (or multiple databases) being described.

However, I am confused, because in the code we only create a table that "points" to metadata. After that, when we call the create_all method on metadata (empty by far), pointing to the database (which is pointed by engine).

Probably my question is silly, but:

How does python exactly connect these instances? Probably the declaration of the census table links metadata to the column names in a two-sided way.


Note: The code is from an exercise from datacamp course.

1 Answers
Related