Python Forum
[solved] What is the best/pytonic way to import with dependency ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[solved] What is the best/pytonic way to import with dependency ?
#1
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.
[Image: NfRQr9R.jpg]
Reply
#2
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).
Reply
#3
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
[Image: NfRQr9R.jpg]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Solved] Import syntax SpongeB0B 1 784 Dec-28-2022, 08:37 AM
Last Post: Gribouillis
  Request Dependency warning thetechnodino 0 942 Dec-20-2022, 02:12 AM
Last Post: thetechnodino
  Circular import dependency hobbyist 9 3,887 Feb-23-2021, 11:57 AM
Last Post: Gribouillis
  Poetry Dependency general Help felipesodre 0 1,455 Jan-14-2021, 07:46 PM
Last Post: felipesodre
  Installing nltk dependency Eshwar 0 1,842 Aug-30-2020, 06:10 PM
Last Post: Eshwar
  How do I change wx version dependency? belfacode 0 1,570 May-17-2020, 09:18 AM
Last Post: belfacode
  Module Dependency installation error draems 10 10,269 Feb-12-2017, 08:18 AM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020