The python importing system vaguely works as follows.
- A line like
import foo is executed.
- Python looks through the directories in
sys.path which is a list in the order in which they occur. The first entry in sys.path is the directory in which the main file lives.
- When Python finds a file named "foo.py", it executes it and places the global namespace of that file in the module
sys.modules['foo'].
- Python binds that module to the name
foo in the scope in which the original import occurs.
So when you name the file random.py, python finds that file before it searches through the files in the standard library. You are "shadowing" the random module with your file.
This is simplified and doesn't give the full picture. For example, it ignores .pyc files.
TryPyPy'sanswer.