Python Forum

Full Version: [solved] What is the best/pytonic way to import with dependency ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
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).
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