Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why python requires us to use from statement when we have already loaded a module using import

Tags:

python

When we import a module, say os, aren't we importing everything in it?

Then what's the use of from moduleName import (delimiter) should be added to the file in order for us to use its constants? and bunch of other things.

Can any one explain the exactly what from moduleName does when we actually have already loaded the module using import?

like image 298
Mostafa Talebi Avatar asked May 01 '26 07:05

Mostafa Talebi


2 Answers

When you just do import sys for example, you do input everything in it. When you do a from sys import exit you import that specific module to be used without its first module name. Basically, if you use the from sys import exit statment you can just call:

exit()

Instead of:

sys.exit()

It's just a way to save less time writing the full sys.exit() statement. If you use it to load constants, you just allow yourself to write shorter statements to write something. If you have questions just ask!

like image 142
Remolten Avatar answered May 02 '26 21:05

Remolten


Suppose I want to use os.path.abspath. I can import os, and type os.path.abspath every time I want to use it. Or I can write from os.path import abspath, and now I just need to type abspath.

The utility of something like:

import os
from os.path import abspath

Is that I can still reference other objects defined in os, like os.path.splitext, but if I use abspath frequently, I only need to type abspath.

like image 43
jme Avatar answered May 02 '26 20:05

jme



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!