Error in import: module 'random' has no attribute 'randint'

1

I was testing the corrected code for this question: Modify global variables . And when I try to execute it in the terminal it throws me an error that says that the% random module does not have the randint attribute (which does not seem to make any sense to me):

  

random = random.randint (1,10)
  AttributeError: module 'random' has no attribute 'randint'

For what it's worth, I'm running it on a PC with Ubuntu Gnome with Anaconda installed.

    
asked by MahaSaka 22.09.2017 в 00:33
source

1 answer

2

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 /usr/local/lib/python .

  • 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.

        
    answered by 22.09.2017 / 14:06
    source