Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hierarchical python imports

Tags:

python

So I have two modules A and B, and another installed module C. Say I use some methods of C in A and B. I also need module A in B. So logically my imports would be :

A :

import C

B :

import A

Logic would tell me that B would contain functions from A and C. However this doesnt work this way by default. In the sense that to refer to any functions in C in module A, we need the extra level of namespace reference

A.C.some_c_module()

I found out that we can import C in both A and B without the use of pesky "C language like" ifdef clones,and it would work fine. My question is, does importing such modules twice come with a penalty? In the sense that is python smart enough to know that A.C.some_module == C.some_module? Or am I just being a bad boy by doing this?

like image 419
Laz Avatar asked Jan 25 '26 01:01

Laz


1 Answers

Importing a module twice doesn't result in it being loaded twice. Python loads the module once and keeps a reference to it. So yes, Python is smart enough to know that the two versions are the same. You can import the module as much as you want and it will only "cost" you once.

Incidentally, the reason that "B would contain functions from A and C" is false is that when you do import C in A.py, A does not "contain functions from C". Rather, A contains a reference to C itself. So when you import A from inside B, you get the reference to C, not references to the functions inside C. If you import individual parts of C directly into A's namespace by using from C import blahBlah, then when you import A you will have access to those functions as members of A.

# A.py
from C import blah

# B.py
import A
A.blah # this will work
like image 72
BrenBarn Avatar answered Jan 27 '26 15:01

BrenBarn