How to Fix AttributeError: ‘module’ object has no attribute ‘choice’

Diagram of module object has no attribute choice

Diagram

AttributeError: ‘module’ object has no attribute ‘choice’ error typically occurs when you try to “access the choice() function from a module that doesn’t have that attribute.”

How to fix it?

To fix the AttributeError: ‘module’ object has no attribute ‘choice’ error, ensure that the module you are trying to use exists and that the attribute “choice” is still available.

Example 1

import random

main_list = [1, 2, 3, 4, 5]
random_choice = random.choice(main_list)

print(random_choice)

Output

3

Alternatively, you can use the “hasattr()” function on Python modules to check if the attribute exists in the specific module.

Example 2

import random

if hasattr(random, "choice"):
  print("The 'choice' attribute exists in the 'random' module.")
else:
  print("The 'choice' attribute does not exist in the 'random' module.")

Output

The 'choice' attribute exists in the 'random' module.

I hope this will help you fix your error!

Related posts

AttributeError: ‘module’ object has no attribute ‘drawMatches’

AttributeError: ‘module’ object has no attribute ‘webdriver’

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.