What is the best way to import for optimizing code?

Viewed 95

Im currently using:

import os

Should I be importing everything separately like this:

from os import listdir, chdir, path, getcwd

I'm looking to get my compiled .exe as small in size and optimized as possible. Is it worth doing this or does python not include unused functions and classes when compiling?

Im using pyinstaller

1 Answers

The import os method is more efficient in terms of execution time.

If we import the entire module:

import os

def list():
    print(os.listdir('.'))

it executes in 0.074s, but when importing one method only:

from os import listdir

def list():
    print(listdir('.'))

then it takes 0.076s.

Here I used the timeit module to time the execution of the above functions.

Related