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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With