So, I was learning about Python modules and according to my understanding when we try import
a module in our code, python looks if the module is present in sys.path
and if it is not then a ModuleNotFoundError
is raised.
Adding locations to sys.path
So, suppose I want to import from a location that does not exist in sys.path
by default, I can simply append this new location to sys.path
and everything works fine as shown in the snippet below.
~/Documents/python-modules/usemymodule.py
import sys
sys.path.append("/home/som/Documents/modules")
import mymodule
mymodule.yell("Hello World")
~/Documents/python-modules/modules/mymodule.py
def yell(txt):
print(f"{txt.upper()}")
Clearing sys.path
My doubt is when I clear the entire sys.path
list, then I should not be able to import any modules but to my surprise I can still import built-in modules. The code below works fine.
import sys
sys.path.clear()
import math
math.ceil(10.2)
I thought it could be possible that python internally doesn't use sys.path
, sys.path
is just a shallow copy of the original list that python uses, but then how does adding to sys.path
works and why is it that after clearing I can only import built-in modules and not custom modules.
I am really stuck, any help would be really nice. Also, there's a similar question to this but it doesn't answer my doubts.