pagination_needed ссылается перед назначением

#python #variables #discord #discord.py #python-3.8

#python #переменные #Discord #discord.py #python-3.8

Вопрос:

     @commands.command()
    async def tags(self, ctx):
        global names
        names = []
        async with aiosqlite.connect('s137_guild_values') as db:
            async with db.execute('SELECT name FROM tag_list WHERE guild_id = ?', (ctx.guild.id,)) as cursor:
                async for row in cursor:
                    value = row
                    value = list(value)
                    names.append(value[0])
        if len(names) != 0:
            STOP = False
            global pagination_dict
            pagination_dict = {}
            global amount_tags
            amount_tags = len(names)
            for x in range(1, self.max_pages):
                if (math.ceil(amount_tags / x) == self.pagination_value):
                    needed_pagination = x
                    break
            current_page = 1
            var = 1
            counter = 0
            counter_all = 0
            counter_all_eq = len(names)
            index = 0
            while True:
                pagination_dict['Page {}'.format(var)] = {}
                msg = ""
                for x in range(0, (len(names))):
                    msg  = '• {}n'.format(names[index])
                    names.remove(names[index])
                    counter  = 1
                    counter_all  = 1
                    if (len(names) == 0) and (counter != self.pagination_value):
                        counter = self.pagination_value
                    if counter == self.pagination_value:
                        counter = 0
                        pagination_dict['Page {}'.format(var)]['Content'] = msg
                        msg = ""
                        var  = 1
                        break
                if (var >= needed_pagination) and (counter_all == counter_all_eq):
                    break
            txt = "Current Page: {}/{}".format("1", needed_pagination)
            embed = discord.Embed(title="Tags ({})".format(amount_tags), description=pagination_dict['Page {}'.format(str(current_page))]['Content'], timestamp=ctx.message.created_at, colour=discord.Colour.blue())
            embed.set_footer(text=txt)
            msg = await ctx.send(embed=embed)
            for ele in self.emojis:
                await msg.add_reaction(ele)
            async def Main(ctx, msg, needed_pagination, current_page, STOP, embed, txt):
                current_page = 1
                STOP = False
                while STOP == False:
                    def check(reaction, user):
                        return (str(reaction.emoji) and user == ctx.author) and (msg.id == reaction.message.id)

                    try:
                        reaction, user = await self.client.wait_for('reaction_add', timeout=60.0, check=check)
                    except asyncio.TimeoutError:
                        await msg.delete()
                        await ctx.message.delete()
                        STOP = True
                    if reaction.emoji == '⏪':
                        if current_page != 1:
                            current_page -= 1
                            embed = discord.Embed(title="Tags ({})".format(amount_tags), description=pagination_dict['Page {}'.format(current_page)]['Content'], timestamp=ctx.message.created_at, colour=discord.Colour.blue())
                            txt = "Current Page: {}/{}".format(current_page, needed_pagination)
                            embed.set_footer(text=txt)
                            await msg.edit(embed=embed)
                            await msg.remove_reaction(reaction, ctx.author)
                        else:
                            await msg.remove_reaction(reaction, ctx.author)
                    elif reaction.emoji == '⏩':
                        if current_page != (needed_pagination):
                            current_page  = 1
                            embed = discord.Embed(title="Tags ({})".format(amount_tags), description=pagination_dict['Page {}'.format(current_page)]['Content'], timestamp=ctx.message.created_at, colour=discord.Colour.blue())
                            txt = "Current Page: {}/{}".format(current_page, needed_pagination)
                            embed.set_footer(text=txt)
                            await msg.edit(embed=embed)
                            await msg.remove_reaction(reaction, ctx.author)
                        else:
                            await msg.remove_reaction(reaction, ctx.author)
                    elif reaction.emoji == '⏹️':
                        await msg.delete()
                        await ctx.message.delete()
                        STOP = True
            x = 0
            if x == 0:
                future = asyncio.ensure_future(Main(ctx, msg, needed_pagination, current_page, False, embed, txt))
                x  = 1
        else:
            await ctx.send("There Are No Tags On This Server!")
  

Я сам все это закодировал, однако столкнулся с проблемой, в которой говорится, что «pagination_needed» ссылается перед назначением.

Я понятия не имею, почему он так говорит.

Я уже некоторое время пытаюсь выяснить, что не так, поэтому, если кто-нибудь знает, я был бы рад. Я бы хотел начать пробовать некоторые методы, как это исправить, как только мне не терпелось снова запустить эту команду. Так что любые предложения были бы замечательными.

Комментарии:

1. Какова точная ошибка с трассировкой? Это имя нигде не появляется в этом коде.

2. @Carcigenicate Я думаю, они имеют в виду needed_pagination .

3. @Cloud Вы, вероятно, правы. Было бы неплохо уточнить, поскольку они ссылаются на «pagination_needed» в двух отдельных местах вопроса.

4. Предполагая, что вы имеете в виду needed_pagination , что эта переменная существует только в том случае, если (math.ceil(amount_tags / x) == self.pagination_value) она имеет значение true . Какое значение вы хотите, чтобы оно было, если этот for цикл проходит весь путь, не найдя удовлетворительного значения x (или если self.max_pages <= 0)?

5. Я выяснил, что было не так, ну, частично я действительно не знаю, почему, но просто создал две функции с единственной разницей if (math.ceil(amount_tags / x) 1 == self.pagination_value): , и if (math.ceil(amount_tags / x) == self.pagination_value): поэтому, если переменная none, я запускаю вторую

Ответ №1:

Я исправил это, добавив две разные функции.

Один для добавления 1 к результату math.ceil , а другой нет.

Это сработало.