why does the *built-in* python module 'sys' need to be explicitly imported with an 'import' statement?

Viewed 123

The python documentation says:

"One particular module deserves some attention: sys, which is built into every Python interpreter."

My understanding is that if a module is built into the Python interpreter itself, then there is no need for an explicit import statement. If the sys module is built-in the Python interpreter, then why is an explicit import statement required for the sys module?

2 Answers

sys is imported at Python startup. So when you import sys, it does not actually do anything except bind a variable name to the already-existing module.

When creating a module instance, there is no reason to have the sys name bound in the module scope when many (probably most) modules don't need to use sys. So, that name is not in scope by default.

import performs two functions:

  1. It loads the module from disk, initializing and executing it.
  2. It adds the module to the local namespace.

With "built-in" modules item 1 is not an issue, but item 2 is still important; without it the code would throw a NameError.

Related