Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 29, 2021 02:42 am GMT

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 sitesite.addsitedir('/home/xqy/dev/python3/pylib')import DBdb = DB.connectlocaldb()

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("
".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.


Original Link: https://dev.to/antlossway/python-module-has-no-attribute-error-4753

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To