Frequent error in Python by beginners is:

AttributeError: module 'cld2' has no attribute 'detect'

Several reasons can cause this problem:

In this post I'll put examples for each case:

Bad python file name

Let say that we want to import a module named cld2 and we want to test this module with python file. And we decide to name our file cld2.py. In this case we end with this error:

import cld2

isReliable, textBytesFound, details = cld2.detect("voulez vous manger avec moi")
print('  reliable: %s' % (isReliable != 0))
print('  textBytes: %s' % textBytesFound)
print('  details: %s' % str(details))

result:

AttributeError: module 'cld2' has no attribute 'detect'

After renaming our file to something else the problem disappears.

Wrong or missing import

If you do mistake with your import you may end with this error or a similar one. So instead the above import you can do something like:

Example 1

File cld2X.py

from langdetectX import detect

isReliable, textBytesFound, details = detect.detect("王明:那是杂志吗")
print('  reliable: %s' % (isReliable != 0))
print('  textBytes: %s' % textBytesFound)
print('  details: %s' % str(details))

File langdetectX.py

from langdetect import detect
from langdetect import detect_langs

# Single language detection
print(detect("War doesn't show who's right, just who's left."))

result:

AttributeError: 'function' object has no attribute 'detect'

Example 2

from cld2 import cld2

isReliable, textBytesFound, details = cld2.detect("voulez vous manger avec moi")
print('  reliable: %s' % (isReliable != 0))
print('  textBytes: %s' % textBytesFound)
print('  details: %s' % str(details))

result:

ImportError: cannot import name 'cld2'

Circular dependency between the modules

Another bad code design can lead to the same Attribute Error. This example of circular dependencies shows what is causing the error and how to avoid it:

Example 1

File xxx.py

import yyy

print (yyy.methodX())

File yyy.py

import xxx

def methodX():
  print ("hi")

result:

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

This is error is raised when you try to execute file xxx.py. The problem can be solved by this code change:

If you change your method yyy.py to:

def methodX():
  import xxx # solving the import problem
  print ("hi")

This will solve the problem. But maybe a better way will be to redesign your code.