Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does 'from modulename import function/variable' put entire module in the sys modules dictionary?

When we do import modulename, then functions and variables get setup in the modulename namespace (global). Any change made to variable for example is globally visible.

When we do from modulename import function or variable, then that function or variable gets loaded in calling modules namespace (local). Any change to variable is not global but only within the calling module.

However, does using from modulename import function or variable - put entire module in the sys modules? Or only the imported function/variable?

like image 915
variable Avatar asked Feb 03 '26 10:02

variable


1 Answers

Even if you import just a selective set of names from a module, the module still needs to be fully compiled and executed for the specified names to be imported, so yes, using from module_name import variable_name does put the entire module into the module cache.

Since imported modules are cached in the sys.modules dict in Python, you can verify the behavior by outputting the difference between the keys of sys.modules before and after an importation:

import sys
modules = sys.modules.copy()
from math import sqrt # selectively import just sqrt from the math module
print(list(sys.modules.keys() - modules.keys()))

This outputs:

['math']

And you can then access other variables in the math module even though you imported only sqrt from math:

print(sys.modules['math'].pi)

This outputs:

3.141592653589793
like image 199
blhsing Avatar answered Feb 05 '26 00:02

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!