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?
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.
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.
4 Answers. Save this answer. Show activity on this post. There's no Python limit on number of imports in a module.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With