2

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?

Jonas Schäfer
  • 20,140
  • 5
  • 55
  • 69
user783836
  • 3,099
  • 2
  • 29
  • 34

1 Answers1

2

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?

No. Python caches imports: A module which is once imported will not be imported again, but the imported module is reused.

You can validate this, by placing a test.py in some directory:

print("foo")

and start a python interpreter:

>>> import test
foo
>>> import test

You’ll notice that the code is only run once.

Or is there a better way to approach this?

Thus, having module-global variables is a valid way to keep state which needs to be kept for the whole program run.

Jonas Schäfer
  • 20,140
  • 5
  • 55
  • 69
  • Thanks Jonas, that really cleared a lot of things up for me. Also enabled me to find this SO question that has a good answer on how import actually works: http://stackoverflow.com/questions/1699108/local-import-statements-in-python – user783836 Aug 16 '14 at 18:05