Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, importing twice with class instantiation?

Tags:

python

In models.py I have:

...
db = SQLAlchemy(app)

class User(db.Document):
...

In my app both serve.py and models.py call:

from models import User 

Is that double import going to instantiate the db twice and potentially cause a problem?

like image 869
Johnston Avatar asked Dec 16 '13 11:12

Johnston


2 Answers

Is that double import going to instantiate the db twice and potentially cause a problem?

No it will not. Once a module is imported it remains available regardless of any further imports via the import statement.

The module is stored in sys.modules once imported.

If you want to reload the module you have to use reload(module).

Example: bar.py

xs = [1, 2, 3]

Importing twice:

>>> from bar import xs
>>> id(xs)
140211778767256
>>> import bar
>>> id(bar.xs)
140211778767256

Notice that the identities are identical?

Caching:

>>> import sys
>>> sys.modules["bar"] is bar
True
like image 173
James Mills Avatar answered Oct 31 '22 13:10

James Mills


No, it won’t. Imports are cached in Python, so importing the same module again will not cause it to be executed again.

You can easily confirm that btw. if you just put a print into the module you are importing. If you see the output multiple times, you would be executing the module multiple times. But that simply doesn’t happen.

like image 38
poke Avatar answered Oct 31 '22 14:10

poke