Python Forum
[solved] What is the best/pytonic way to import with dependency ? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: [solved] What is the best/pytonic way to import with dependency ? (/thread-40311.html)



[solved] What is the best/pytonic way to import with dependency ? - SpongeB0B - Jul-08-2023

Hi everyone,

I would like to create a module (let's call it FooBar) that I could import in few of my "main" programs.

But the functions within FooBar rely on other modules... that are already imported inside the main program.

is there a way that the FooBar doesn't need to import them too ?

Because the following is not working.

MAIN.py
import sqlite3
from FooBar import *

test()
FooBar.py
def test():
    with sqlite3.connect('aSQLitedb') as connection....
Error:
NameError: name ‘sqlite3’ is not defined
Thanks.


RE: What is the best/pytonic way to import with dependency ? - deanhystad - Jul-09-2023

If importing the module added names to the module's namespace, it would make it nearly impossible to write modules. Importing sqlite3 into your progam could break sqlite3 if any of your functions or classes happened to have the same name as attributes in your program.

You should not worry about modules being imported multiple times. The first import may be expensive, but subsequent imports are little more than a dictionary lookup. When you write foobar.py you should not have to care if main.py imports sqlite3. If foobar uses sqlite3, it should import the module. If main.py also uses sqlite3, it should import the module. You should not care that the module is imported 2 (or 10 or 100) times. After the first import, the cost of importing the module is nearly zero (in time and memory).


RE: What is the best/pytonic way to import with dependency ? - SpongeB0B - Jul-09-2023

Thank you so much @deanhystad !

This is enlightening ! It's "funny" because on all the tutorial that I read about modules & package never someone mentioned the cost of importing or the mechanism of importing..

Thumbs Up