How to get all variables of some module in that module

Peter Otten __peter__ at web.de
Tue Oct 21 09:37:39 CEST 2008


Alex Gusarov wrote:

> Hello, I have a following module and in its end I want to initalize
> collection of tables:
> 
> Module:
> 
> from sqlalchemy import *
> 
> metadata = MetaData()
> 
> calendars_table = Table('calendars', metadata,
>     Column('id', Integer, primary_key=True),
>     Column('title', Unicode(50)),
>     Column('color', Unicode(6)),
> )
> 
> events_table = Table('events', metadata,
>     Column('id', Integer, primary_key=True),
>     Column('calendar', Integer, ForeignKey('calendars.id')),
>     Column('date', Date),
>     Column('title', Unicode(50)),
>     Column('description', Unicode(1000)),
>     Column('color', Unicode(6)),
> )
> 
> tables_collection = {}
> 
> Here I want to get all Table instances of current module and put them
> into dictionary by names, but I don't know how I can get all variables
> of current module in the end of this module. Please, give me a hint.

tables_collection = dict((k, v) for k, v in globals().iteritems()
                         if isinstance(v, Table))

Alternatively you may consider using metadata.tables. The keys will then
be "calendars" and "events" rather than the variable names.

Peter



More information about the Python-list mailing list