Johnston
Johnston

Reputation: 20884

In Python, importing twice with class instantiation?

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?

Upvotes: 6

Views: 1479

Answers (2)

James Mills
James Mills

Reputation: 19040

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

Upvotes: 11

poke
poke

Reputation: 387795

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.

Upvotes: 3

Related Questions