iammax
iammax

Reputation: 473

Python efficiency: importing things in things I am importing?

Let's say I am making a project, let's call it master.py as it is the master file.

#this is master.py
import a
import b
for i in range (whatever):
 for j in range (whatever):
  a.main(i)
  b.main(j)

a and b are other sub-functions which I have made, and are in other text files (for easier tweaking). Now let's say a is:

#this is a.py
def main(i):
 from numpy import sin
 return sin(i)

and b:

#this is b.py
def main(j):
 from random import uniform
 return uniform(0, j)

master.py calls functions a and b a lot of times. Each time it does, it imports sin in a, and uniform in b. This can't be efficient, but I don't know a way around it (besides putting a and b in the same text file as master.py, which I don't want to do for debugging reasons). I have tried putting the statements for importing sin and uniform in master.py instead, but then when it calls a and b, it fails because sin and uniform aren't imported. I guess it has to import them in the subroutines? Can I somehow import sin and uniform in master.py and pass them along to a and b so I don't have to import each time?

Upvotes: 0

Views: 563

Answers (1)

Eric Fulmer
Eric Fulmer

Reputation: 706

Have you tried importing at the top of a.py and b.py?

# a.py
from numpy import sin

def main(i):
    return sin(i)

and:

# b.py
from random import uniform

def main(j):
    return uniform(j)

You would not need to do the imports of random.uniform and numpy.sin in master.py because those functions. They're called by other functions in other modules; so the imports are needed in those other modules.

As well, this Python Wiki page on performance indicates that the importsat the top of the file is superior for performance.

Upvotes: 1

Related Questions