Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it more efficient to use "import <module>" or "from <module> import <func>"?

Tags:

python

import

Say I only needed to use findall() from the re module, is it more efficient to do:

from re import findall

or

import re

Is there actually any difference in speed/memory usage etc?

like image 343
Ashy Avatar asked Dec 06 '08 20:12

Ashy


People also ask

Is from import faster than import?

There is a difference, because in the import x version there are two name lookups: one for the module name, and the second for the function name; on the other hand, using from x import y , you have only one lookup. As you can see, using the form from x import y is a bit faster.

What are the two ways of importing a module which one is more beneficial?

The 4 ways to import a module Import specific things from the module: pycon from random import choice, randint. Import the whole module and rename it, usually using a shorter variable name: pycon import pandas as pd. Import specific things from the module and rename them as you're importing them: pycon from os.

What is the difference between import module and from module import *?

The difference between import and from import in Python is: import imports the whole library. from import imports a specific member or members of the library.


2 Answers

There is no difference on the import, however there is a small difference on access.

When you access the function as

re.findall() 

python will need to first find the module in the global scope and then find findall in modules dict. May make a difference if you are calling it inside a loop thousands of times.

like image 181
Kozyarchuk Avatar answered Oct 10 '22 02:10

Kozyarchuk


When in doubt, time it:

from timeit import Timer

print Timer("""re.findall(r"\d+", "fg12f 1414 21af 144")""", "import re").timeit()
print Timer("""findall(r"\d+", "fg12f 1414 21af 144")""", "from re import findall").timeit()

I get the following results, using the minimum of 5 repetitions of 10,000,000 calls:

re.findall(): 123.444600105
findall(): 122.056155205

There appears to be a very slight usage advantage to using findall() directly, rather than re.findall().

However, the actual import statements differ in their speed by a significant amount. On my computer, I get the following results:

>>> Timer("import re").timeit()
2.39156508446
>>> Timer("from re import findall").timeit()
4.41387701035

So import re appears to be approximately twice as fast to execute. Presumably, though, execution of the imported code is your bottleneck, rather than the actual import.

like image 40
Noah Avatar answered Oct 10 '22 00:10

Noah