1

Since os is a module instead of a package, import os.path should fail. For comparison:

>>> import os.sys
Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
    import os.sys
ModuleNotFoundError: No module named 'os.sys'; 'os' is not a package

Note that os.sys is available:

>>> import os
>>> os.sys
<module 'sys' (built-in)>

So, how does import os.path work? Are there any other cases of something like this?

2

1 Answer 1

-6

The reason import os.path works—even though os is a module and not a package—is because os manually sets the path attribute during import. It does something like this internally:

python

importposixpath # or ntpath depending on OS path = posixpath

So when you do import os.path, Python sees that os has an attribute path, which points to the actual path module (like posixpath or ntpath). It’s not relying on package-style importing.

Other examples:
Yes! The sys module does something similar. For example, sys.modules is not a separate module but a dictionary attached to sys.

New contributor
Ahmad Minhas is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1
  • 1
    LLM-generated content is not allowed here. Commented 4 hours ago

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.