I am following this tutorial to see why Python doesn't recognize an environment variable that was set at the Conda prompt (using CMD syntax, as this is an Anaconda installation on Windows 10).
It requires the os
module, and as part of my getting familiar with Python, I decided to test whether os
was already imported. Testing the presence of a module requires the sys
module (as described here).
Strangely, right after importing sys
, I found that os
was imported without me having to do so. I find this odd, as most of my googling shows that you have to import them individually, e.g., here.
Does importing sys
also impart os
, as it seems to? If so, why is it common to import both individually?
I can't test for the presence of os
before importing sys
, as I need sys
to test for the presence of modules.
Here is the code that shows the apparent presence of os
from importing sys
, formatted for readability. It starts from the Conda prompt in Windows. The Conda environment is "py39", which is for Python 3.9:
(py39) C:\Users\User.Name > python
Python 3.9.16 (main, Mar 8 2023, 10:39:24)
[MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license"
for more information.
>>> import sys
>>> "os" in sys.modules
True
Afternote: Thanks to Zero's answer, I found this code to be more what I'm looking for. After loading sys
, the appropriate test is ( 'os' in sys.modules ) and ( 'os' in dir() )
:
(py39) C:\Users\User.Name > python
'os' in dir() # False
import sys
'os' in sys.modules , 'os' in dir() # (True, False)
( 'os' in sys.modules ) and ( 'os' in dir() ) # False
import os
'os' in sys.modules , 'os' in dir() # (True, True)
( 'os' in sys.modules ) and ( 'os' in dir() ) # True
sys.modules
shows whether the module has been imported anywhere (presumably in the code that the Python interpreter has executed) while dir()
indicates whether the module name is in the current namespace. Thanks to Carcigenicate for clarifying this point, and I hope that I understood it properly.