Search code examples
pythonclassattributeerror

instance has no attribute (python)


I have a weird issue, which is probably easy to resolve.

I have a class Database with an __init__ and an executeDictMore method (among others).

class Database():
    def __init__(self, database, server,login, password ):
        self.database = database
        my_conv = { FIELD_TYPE.LONG: int }
        self.conn = MySQLdb.Connection(user=login, passwd=password, db=self.database, host=server, conv=my_conv)
        self.cursor = self.conn.cursor()

    def executeDictMore(self, query):
        self.cursor.execute(query)
        data = self.cursor.fetchall()
        if data == None :
            return None
        result = []
        for d in data:
            desc = self.cursor.description
            dict = {}
            for (name, value) in zip(desc, d) :
                dict[name[0]] = value
            result.append(dict)
        return result

Then I instantiate this class in a file db_functions.py :

from Database import Database
db = Database()

And I call the executeDictMore method from a function of db_functions :

def test(id):
    query = "SELECT * FROM table WHERE table_id=%s;" %(id)
    return db.executeDictMore(query)

Now comes the weird part. If I import db_functions and call db_functions.test(id) from a python console:

import db_functions
t = db_functions.test(12)

it works just fine. But if I do the same thing from another python file I get the following error :

AttributeError: Database instance has no attribute 'executeDictMore'

I really don't understand what is going on here. I don't think I have another Database class interfering. And I append the folder where the modules are in sys.path, so it should call the right module anyway.

If someone has an idea, it's very welcome.


Solution

  • You have another Database module or package in your path somewhere, and it is getting imported instead.

    To diagnose where that other module is living, add:

    import Database
    print Database.__file__
    

    before the from Database import Database line; it'll print the filename of the module. You'll have to rename one or the other module to not conflict.