It is important not to create a module called
random.py in the same directory where the script is (or in the current working directory in the case of the interactive interpreter) that attempts to import
random.randint of the stdlib. In general, try to avoid naming our script with names that may conflict with the standard library or with other external libraries installed (such as naming modules with the word "django" when working with this framework).
This has to do with what directories and in what order the imports are resolved. When a module is imported (absolute amount), for example using:
>>> import random
The interpreter looks for that module in the following locations and in this order:
Built-in modules (stdlib).
The directory that contains the script or the current directory if no script is specified (for example when executing the interactive interpreter in the terminal).
Search the PYTHONPATH
Default path dependent on installation, for example
So what happens here? In the documentation give us the answer:
After initialization, Python programs can modify
sys.path . The directory containing the script that is running is placed at the beginning of the search path, ahead of the standard library path . This means that the scripts of that directory will be loaded instead of the modules of the same name of the stdlib. This is a mistake, unless the replacement is thought.
This also happens when a script that is inside a package is executed, since python will not interpret that directory as a package, thus adding the working directory to the
PYTHONPATH as commented above.