5

I have created a module with multiple small user-defined functions. Many of those functions require different library function. Now, I want to know what is a better practice - to import all the libraries in the module, or import the libraries within the functions? Is there any difference in terms of performance?

Example code

my_module.py

from math import exp
from numpy import mean,random

def logit(x):
    return exp(x)/(1+exp(x))

def sample_mean(mu,sigma,size):
    return mean(random.normal(mu,sigma,size))

Or

def logit(x):
    from math import exp
    return exp(x)/(1+exp(x))

def sample_mean(mu,sigma,size):
    from numpy import mean,random
    return mean(random.normal(mu,sigma,size))

P.S.

This is just a sample code to explain my dilemma. Don't tell me that there are ready made functions to use instead of these user-defined functions. I already know that

Meghdeep Ray
  • 5,262
  • 4
  • 34
  • 58
Nilabja Ray
  • 67
  • 1
  • 6

2 Answers2

2

It won't be significantly beneficial. Python style guides encourage programmers to place all imports at the beginning of the module file.
Importing at the start is part of the philosophy and style of Python.
As you've shown in your code a way of improving efficiency is importing only what you need like : from numpy import mean,random.
If you do import inside a function it will give you a minor efficiency advantage but unless you're working on an extremely time critical application it's better to go with the general Pythonic style of importing everything at the start.

Module importing is quite fast, but not instant. This means that:

  • Putting the imports at the top of the module is a trivial cost that's only paid once.
  • Putting the imports within a function will cause calls to that function to take longer.

So if you care about efficiency, put the imports at the top. Only move them into a function if your profiling shows that would help.

Meghdeep Ray
  • 5,262
  • 4
  • 34
  • 58
  • imports are cached, though, so it's not that costly to have imports in a function, because all it does on the second time around is "check if import is in sys.modules, continue on happily if it is." – NightShadeQueen Aug 04 '15 at 19:15
2

Depends on how related your functions are, but usually at the module level is cleaner. If your functions are not related, then having different imports for each will be completely fine and will hint at their independence. At that point, I would just make two separate python files.

The Brofessor
  • 1,008
  • 6
  • 15