I\'m having problems with Python\'s import random function. It seems that import random
and from random import random
are importing different thing
The 'random' module is a package from the python standard library, as well as a function defined in this package.
Using 'import random' imports the package, which you can then use the function from this package: 'random.random()'. You can use any other function from the 'random' package as well.
You can also tell python to specifically import only the random function from the package random: 'from random import random'. Then you can only use the function 'random()', and should not specify the package it comes from. However you cannot use any other function from the random package, because they have not been imported if you use 'from random import random'.
If you are using PyDev or other clever IDE, make sure it did not import the module automatically, overriding your import. It can be especially confusing here, when module name is equal to a function name, because the error thrown is not a NameError
. In my case I added
import random
and later used it:
r = random.radom()
but got:
AttributeError: 'builtin_function_or_method' object has no attribute 'random'
Only after searching I found that PyDev automatically added the line
from random import random
to the end of my imports, so I was in fact calling attribute random
of method random
. Solution is to delete the automatic import or use it and call the random()
method directly.
If you use from random import random
, you must call randint() like so: randint(1,5)
. If you use import random
, you call it like so: random.randint(1,5)
.
You have to import the random function, from the random module before you can use it use it
In [1]: from random import random
In [2]: random()
Out[2]: 0.5607917948041573
import random
imports the random module, which contains a variety of things to do with random number generation. Among these is the random() function, which generates random numbers between 0 and 1.
Doing the import this way this requires you to use the syntax random.random()
.
The random function can also be imported from the module separately:
from random import random
This allows you to then just call random()
directly.
Well, yes, they import different things. import random
imports the random
module, from random import random
imports the random
function from the random
module. This is actually a good example of why when designing an API in Python, it's often a good idea to try to avoid naming modules and their members the same thing.