'module' object has no attribute 'choice' - trying to use random.choice

AMHD picture AMHD · Sep 6, 2014 · Viewed 41.4k times · Source

Could someone please tell me what I may be doing wrong. I keep getting this message when I run my python code:

import random

foo = ['a', 'b', 'c', 'd', 'e']

random_item = random.choice(foo)

print random_item

Error

AttributeError: 'module' object has no attribute 'choice'

Answer

Cory Kramer picture Cory Kramer · Sep 6, 2014

Shot in the dark: You probably named your script random.py. Do not name your script the same name as the module.

I say this because the random module indeed has a choice method, so the import is probably grabbing the wrong (read: undesired) module.