To help explain this we'll be using the dir() function: with specific examples. And how you can check these for yourself.
What's the use of '.' in import statements?
'.' quite literally sets the parent directory of import search.
This is reserved for packages, and is related to use of the '__path__ '
attribute.
You can check this yourself like so. Lets go ahead and import numpy and math:
import numpy, math
print(dir(numpy))
and look for the '__path__'
attribute to determine if something is a package or not: Finding '__path__'
you know numpy is a package.
Why it does not work when trying import math.floor
?
First, we need to understand what and how import "whatever"
is searching.
For simplicity you can think of:
import whatever = look for "whatever", if found: look in "whatever" for '__name__'
, if '__name__'
not in "whatever" raise Error ModuleNotFound
Let's look at import math
:
python will search for math, and once found, will search in math for its '__name__'
attribute, because this is what import uses to resolve its pointer assignment (this is relevant, but not to this explanation).
You can use:
print(dir(math))
and look for '__name__'
attribute to check whether something is a module or not: Finding '__name__'
attribute, you know math is a module.
and if you were to try
print(dir(math.floor))
you will not find '__name__'
because floor is not a module and cannot be "found" by python import math.floor
or import floor
.
Therefore when you try import math.floor
(assigning math as the parent directory is irrelevant).
python will look for math; finding math, python will search in math for floor; finding floor, python will search for floor's '__name__ '
attribute; and unable to find the '__name__'
attribute it will raise an error ModuleNotFound.
Using from
alters the search pattern so that it becomes look for (module, attribute - '__specific__'
) instead of (module, attribute - ' __name__'
)
in the case of from math import floor
this means python will search for math's '__floor__'
attribute' instead of math's '__name__'
attribute. It will find the floor attribute in math and work fine.