DEV Community

Quinn
Quinn

Posted on

python: module has no attribute error

Problem

I have a directory ~/dev/python3/pylib, which contains handy small modules. One of them is DB.py, which defines functions to connect to different databases.

If a script requires connection to a database, I can simply do

import site
site.addsitedir('/home/xqy/dev/python3/pylib')
import DB

db = DB.connectlocaldb()
Enter fullscreen mode Exit fullscreen mode

But why I got error like below?

AttributeError: module 'DB' has no attribute 'connectlocaldb'

I checked several times to make sure the lib dir is correct and the file DB.py includes function "connectlocaldb()", but the error still persists.

Reason:

When importing a module, python will go through a list of directories included in sys.path, and searching for the specified module, the first one found will be used.

xqy@voyager:~/dev/python3$ python
Python 3.7.3 (default, Jan 22 2021, 20:04:44)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

import sys
print("\n".join(sys.path))
''
/usr/lib/python37.zip
/usr/lib/python3.7
/usr/lib/python3.7/lib-dynload
/home/xqy/.local/lib/python3.7/site-packages
/usr/local/lib/python3.7/dist-packages
/usr/lib/python3/dist-packages


the empty entry '' means the current directory

There is another DB.py under ~/dev/python3/, as my current directory is ~/dev/python3, the module file ~/dev/python3/DB.py is used instead of /home/xqy/dev/python3/pylib/DB.py

And there is no "connectlocaldb" function in ~/dev/python3/DB.py

We can also find out sys.path using below command

xqy@voyager:~/dev/python3$ python3 -m site
sys.path = [
'/home/xqy/dev/python3',
'/usr/lib/python37.zip',
'/usr/lib/python3.7',
'/usr/lib/python3.7/lib-dynload',
'/home/xqy/.local/lib/python3.7/site-packages',
'/usr/local/lib/python3.7/dist-packages',
'/usr/lib/python3/dist-packages',
]
USER_BASE: '/home/xqy/.local' (exists)
USER_SITE: '/home/xqy/.local/lib/python3.7/site-packages' (exists)
ENABLE_USER_SITE: True

xqy@voyager:~/dev/python3$ cd ~
xqy@voyager:~$ python3 -m site
sys.path = [
'/home/xqy',
'/usr/lib/python37.zip',
'/usr/lib/python3.7',
'/usr/lib/python3.7/lib-dynload',
'/home/xqy/.local/lib/python3.7/site-packages',
'/usr/local/lib/python3.7/dist-packages',
'/usr/lib/python3/dist-packages',
]
USER_BASE: '/home/xqy/.local' (exists)
USER_SITE: '/home/xqy/.local/lib/python3.7/site-packages' (exists)
ENABLE_USER_SITE: True`

Therefore, by deleting file ~/dev/python3/DB.py or changing current directory, the error will not appear any more.

Top comments (0)