0

I want to add new method in Sheet Object (xlrd package), here is the code (in file Sheet.py):
from xlrd.sheet import Sheet
class Sheet(Sheet):
    def dict_reader(self, fieldnames):
        list_dict = []
        for i, _ in enumerate(range(self.nrows)):
            temp_dict = {}
            for j, _ in enumerate(range(self.ncols)):
                temp_dict.update(fieldnames[j], self.cell_value(i, j))
            list_dict.append(temp_dict)
        return list_dict

The problem is that when I call the method, It gives me AttributeError: 'Sheet' object has no attribute 'dict_reader'.
In the file I want to use it (file.py) the code is something like that :

import xlrd
from ..sheet import Sheet
workbook = xlrd.open_workbook(filename)
worksheet = workbook.sheet_by_index(0)
reader = worksheet.dict_reader(columns)

In the init.py file:

from . import Models_directory

My directory structure is something like that (yes, It is Odoo module directory architecture):

Main_directory
    Sheet.py
    Models_directory
        file.py
    __init__.py
CZoellner
  • 13,553
  • 3
  • 25
  • 38
m0r7y
  • 670
  • 1
  • 8
  • 27

2 Answers2

1

It is unwise to have the same name for your class and the class you have imported from an external module. Use something like 'MySheet' and the problem will be solved assuming Sheet or MySheet has the required attribute dict_reader.

ViggyPiggy
  • 127
  • 5
0

This isn't using your class. The worksheet returned by workbook.sheet_by_index(0) is not your Sheet class, but the original. To put your method into this particular instance of Sheet, you can:

import xlrd
import types

def dict_reader(self, fieldnames):
    list_dict = []
    for i, _ in enumerate(range(self.nrows)):
        temp_dict = {}
        for j, _ in enumerate(range(self.ncols)):
            temp_dict.update(fieldnames[j], self.cell_value(i, j))
        list_dict.ap

workbook = xlrd.open_workbook(filename)
worksheet = workbook.sheet_by_index(0)
worksheet.dict_reader = types.MethodType(dict_reader,worksheet)
reader = worksheet.dict_reader(columns)

But this still doesn't run because 'columns' is not defined.

AllAboutMike
  • 121
  • 7
  • GG, that is what I'm looking for. More details here : https://stackoverflow.com/questions/972/adding-a-method-to-an-existing-object-instance – m0r7y Aug 05 '20 at 09:46