I'm starting my first major foray into Python coming from C# and Java. Pretty good so far, but one concept I cannot seem to get a handle on is how to initialise long-lived variables that will be used in many modules and packages?
In C#, I could have an Environment
or Config
class that is instantiated at app startup and passed around through dependency injection or another mechanism that could hold the values.
As a specific example, I am using SQLAlchemy to do my db inserts. I have created a module db.py
that has the db code in that looks like:
engine = create_engine('dburl', echo=True)
conn = engine.connect()
metadata = MetaData()
table_mytable = Table('mypackage', metadata,
Column('id', String, primary_key=True),
Column('mystuff', String),
ins = table_mytable.insert()
def insert():
result = conn.execute(ins)
other code then imports my db
module and makes use of the insert
function to do the inserts.
What I am having trouble with is, everytime I import my db module for use, will the engine
, conn
, metadata
and table_my_table
variables be re-created so essentially for every import I am reconnecting to the db
and re-defining all the meta data?
Is this the correct and expected thing? Or is there a better way to approach this?