Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing Modules - How Much is Too Much?

As a newbie, I've grown fond of importing modules almost by default when I start writing something just because I call on certain functions within them quite a bit (modules like random, time, os, and sys). However, does this impact performance at all? If I only want a specific function in the module, am I better served by asking for it explicitly or should I not care?

like image 980
Kimomaru Avatar asked Feb 28 '13 20:02

Kimomaru


People also ask

What happens if you import a module twice?

The rules are quite simple: the same module is evaluated only once, in other words, the module-level scope is executed just once. If the module, once evaluated, is imported again, it's second evaluation is skipped and the resolved already exports are used.

Which is the correct way to import modules?

To use the module, you have to import it using the import keyword. The function or variables present inside the file can be used in another file by importing the module. This functionality is available in other languages, like typescript, JavaScript, java, ruby, etc.

How many imports can you have in Python?

4 Answers. Save this answer. Show activity on this post. There's no Python limit on number of imports in a module.

What are three way's of importing modules?

The 4 ways to import a moduleImport the whole module using its original name: pycon import random. 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.


1 Answers

When you do from module import name, Python still has to run module, so there is no difference performance-wise.

Generally, if you are only using one thing from a module, the using from x import y is fine, but otherwise, using import x and then x.y results in a lower chance of conflicting names.

The reason for this is that Python doesn't treat functions and classes specially. When you import from a module, all you are doing is taking objects from that module and using them. This is useful, as it makes modules (as well as classes and functions) extremely flexible, but it does mean that Python has to run the whole script for a module before it can import from it (naturally, module writers can work around this by using the if name == "main": idiom to insert code that shouldn't be run on import).

like image 161
Gareth Latty Avatar answered Sep 21 '22 13:09

Gareth Latty