Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import statement in python

Why give full path to call a function when import statement is used to import a module from subpackage of package?

eg . A is package , AA is sub package of A , AA1 is module in AA

import A.AA.AA1

A.AA.AA1.AA1fun()

works correctly

but

AA1.AA1fun()

Why not this and why is 'A' got placed in global namespace why not 'AA1'?

like image 758
harshit Avatar asked Jan 23 '26 16:01

harshit


2 Answers

Let's suppose that we perform an import of these two modules:

import A.AA.AA1
import B.AA.AA1

Which of the two modules would be chosen if you run the following functions?

AA.AA1.fun()
AA.AA1.fun()
AA1.fun()
AA1.fun()

To avoid this ambiguity you have to explicitly put the whole package, subpackage and module path.

A.AA.AA1.fun()
B.AA.AA1.fun()

If you want to avoid having to use the whole path every time, you have the from option:

from A.AA.AA1 import fun
fun()

But, by doing this, the name of the identifier fun is exposed. Therefore, if fun was already assigned to another object previously, it is overridden and now points to the new object in A.AA.AA1.

fun = lambda x: 2*x
from A.AA.AA1 import fun
from B.AA.AA1 import fun

In this last example, after executing these lines of code, fun refers only to the object in module B.AA.AA1.

You can also use the as option to create an alias to the imported module:

import A.AA.AA1 as AAA1
import B.AA.AA1 as BAA1

AAA1.fun()
BAA1.fun()

This way the whole path is abbreviated and avoids ambiguity when executing fun from one module or another.

In this link you can find the documentation: import doc

like image 98
Carlos A. Gómez Avatar answered Jan 26 '26 09:01

Carlos A. Gómez


The main difference is in how import works, please refer to the docs section 5.4.2 for more information. As an example:

import A.AA.AA1

A.AA.AA1.AA1fun()

With as sole import you will have to provide the complete path. On the other hand, if you use a from statement you can use it directly:

from A.AA import AA1

AA1.AA1fun()
like image 42
McBait Avatar answered Jan 26 '26 08:01

McBait



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!