Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the ways to import a module/function?

It is a very basic question, but I have not seen any explanation covering all possible cases so far.

Suppose m1, m2, m3 are module hierarchies, and fun() is a function inside the hierarchy.

I have seen commands like

Version 1

from m1.m2.m3 import fun
fun() #To access the function

Version 2

import m1
m1.m2.m3.fun()

Are they exactly equivalent to

Version 3

import m1.m2
m1.m2.m3.fun()

or

Version 4

from m1.m2 import m3
m3.fun()

Or any other combinations in-between? Is there any relative advantage or disadvantage? Clearly, I would rather like to write fun() while calling the function each time rather than writing m1.m2.m3.fun() but what is the trade off?
From my understanding, version 2 will execute the whole script of m1. But are the others more selective in their execution (and hence possibly get to the __main__ quicker?)

like image 820
Della Avatar asked Feb 06 '26 04:02

Della


1 Answers

Version 1

from m1.m2.m3 import fun
fun() #To access the function

Version 1 is the one to go with if fun is the only function you want from the m1 tree and you can guarantee that no other function inside your script will ever be called fun. If any of the above are not satisfied do not do it, but if the are, do it.


Version 2

import m1
m1.m2.m3.fun()

Version 2 is the one to go with if you want to be able to access everything inside m1. It does lead to more verbose code because you have to carry the m1 with you all the time but it is safer and far less obscure that the equivalent (which should be discouraged) from m1 import *. Note that m1 code will be executed.


Version 3

import m1.m2
m1.m2.m3.fun()

Version 3 is the one to go with if you want to be able to access everything inside m2 but not higher (cannot do m1.more_fun()). Note that m2 code will be executed.


Version 4

from m1.m2 import m3
m3.fun()

Version 4 is the one to go with if you want to be able to access everything inside m3 but not higher (cannot do m1.m2.more_fun()). Note that m3 code will be executed.

like image 169
Ma0 Avatar answered Feb 15 '26 18:02

Ma0