'NoneType' object is not subscriptable не могу понять почему?

'NoneType' object is not subscriptable после выполнения удаления

Вот функция из бота

def del_cat(message):
    try:
        conn = sqlite3.connect("base_ts.sqlite")
        cursor = conn.cursor()
        cursor.execute('SELECT * FROM catalog')
        row = cursor.fetchall()
        cursor.close()
        conn.close()

        name = row[int(message.text)][1]
        category = func.AddCategory(name)
        cat_dict[message.chat.id] = category

        conn = sqlite3.connect("base_ts.sqlite")
        cursor = conn.cursor()
        cursor.execute(f'SELECT * FROM "{name}"')
        row = cursor.fetchall()
        cursor.close()
        conn.close()

        text = ''
        num = 0

        for i in row:
            text = text + '№ ' + str(num) + '   |  ' + str(i[0]) + '\n'
            num += 1

        msg = bot.send_message(chat_id=message.chat.id,
                               text='Выберите номер товара который хотите удалить\n\n'
                                    f'{text}')
        bot.register_next_step_handler(msg, del_cat_2)
    except Exception as e:
        print(e)
        bot.send_message(chat_id=message.chat.id,
                         text='Упсс, что-то пошло не по плану')


def del_cat_2(message):
    try:
        category = cat_dict[message.chat.id]

        conn = sqlite3.connect("base_ts.sqlite")
        cursor = conn.cursor()
        cursor.execute(f"SELECT * FROM '{category.section}'")
        row = cursor.fetchall()

        name_category = row[int(message.text)][2]
        category.category = name_category

        markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
        markup.add('Yes', 'No')

        msg = bot.send_message(chat_id=message.chat.id,
                               text='❕Удалить ⬇️\n'
                                    f'❕{category.category}\n\n'
                                    '❕из раздела ⬇️\n'
                                    f'❕{category.section}  ?',
                               reply_markup=markup)
        bot.register_next_step_handler(msg, del_cat_3)
    except Exception as e:
        print(e)
        bot.send_message(chat_id=message.chat.id,
                         text='Упсс, что-то пошло не по плану')


def del_cat_3(message):
    try:
        if message.text == 'Yes':
            category = cat_dict[message.chat.id]

            func.del_cat_to_section(category.category, category.section)
            bot.send_message(
                chat_id=message.chat.id,
                text=f'✅Товар: {category.category}\n'
                     f'✅Успешно удален из раздела',
                reply_markup=menu.admin_menu
            )
        if message.text == 'No':
            bot.send_message(chat_id=message.chat.id,
                             text='Вы вернулись в меню админа',
                             reply_markup=menu.admin_menu)
    except Exception as e:
        print(e)
        bot.send_message(chat_id=message.chat.id,
                         text='Упсс3, что-то пошло не по плану')

И это с импорта файла как функции ,я подозреваю что проблема в классах но как верно будет

class AddCategory:
    def __init__(self, section):
        self.section = section
        self.cat = None
        self.category = None

class Category:
    def __init__(self, category):
        self.category = category

def del_cat_to_section(section, name_category):
    # Connection
    conn = sqlite3.connect("base_ts.sqlite")
    cursor = conn.cursor()

    # del
    category = cursor.execute(f'SELECT * FROM "{section}" WHERE list = "{name_category}"').fetchone()

    cursor.execute(f"DELETE FROM '{section}' WHERE list = '{name_category}'")
    conn.commit()

    cursor.execute(f"DROP TABLE '{category[2]}'")

    # Close connection
    cursor.close()
    conn.close()

дохожу до 3го делита и 'NoneType' object is not subscriptable

И вот полный трейсбек

Traceback (most recent call last):
  File "C:/Users/Бодянич/Desktop/newbot/main.py", line 732, in del_cat_3
    func.del_cat_to_section(category.category, category.section)
  File "C:\Users\Бодянич\Desktop\newbot\functions.py", line 227, in del_cat_to_section
    cursor.execute(f"DROP TABLE '{category[2]}'")
TypeError: 'NoneType' object is not subscriptable

Ответы (2 шт):

Автор решения: MarianD

Команда

category = cursor.execute(f'SELECT * FROM "{section}" WHERE list = "{name_category}"').fetchone()

не была неудачна (нет такой строки), потому значение переменной category будет None и — следовательно — в команде

cursor.execute(f"DROP TABLE '{category[2]}'")

the expression category[2] raises the exception

TypeError: 'NoneType' object is not subscriptable

Мне не хочет разбираться в том, что вы хотели сделать, но самой ошибки возможно избавиться так, что вместо

cursor.execute(f"DROP TABLE '{category[2]}'")

используете

if cursor:
    cursor.execute(f"DROP TABLE '{category[2]}'")
→ Ссылка
Автор решения: MarianD

Вместо

category = cursor.execute(f'SELECT * FROM "{section}" WHERE list = "{name_category}"').fetchone()

напишите эту команду без присваивания, так:

cursor.execute(f'SELECT * FROM "{section}" WHERE list = "{name_category}"').fetchone()

чтобы не переписать переменную category.

→ Ссылка