Home > Back-end >  Variable not defined even using global python
Variable not defined even using global python

Time:10-11

PYTHON Just started working with cogs in discord.py so I was copying my code around into cogs but one thing that worked before isn't working in a cog and I cannot figure out why. Code sample below.

    sverify_index=0
    sverify_msg_id=""
    @commands.Cog.listener()
    async def on_message(self, message):
        if message.channel.id == 888529033405530183 and message.author.id != 887542628063780864:
                global sverify_index, sverify_msg_id
                sverify_index  = 1
                sverify_list = []
                sverify_list.append(sverify_index)

Currently the error I am getting is

line 19, in on_message
    sverify_index  = 1
NameError: name 'sverify_index' is not defined

Please help.

CodePudding user response:

Based on the indentation and the existence of self, I think you have something like

class Something...:
    sverify_index=0
    sverify_msg_id=""
    @commands.Cog.listener()
    async def on_message(self, message):
         ...

That will make sverify_index and sverify_msg_id class-level variables (shared by all instances of Something...), not global variables.

If you truly want them to be global variables, you can do

sverify_index = 0
sverify_msg_id = ""

class Something...:
    @commands.Cog.listener()
    async def on_message(self, message):
         global sverify_index, sverify_msg_id

to make them real global variables.

CodePudding user response:

As AKX mentioned, they are defined class-level variables currently. In order to have them as global variables, they can be moved out of the class.

An Alternative Approach

Since the question was not about making them global variables, but why they are not accessible when moved to a class, another solution can be to keep them as class-level variables, and then access them like self.sverify_index and self.sverify_msg_id.

So the solution will be as follows

class Something(commands.Cog):
    ...

    sverify_index=0
    sverify_msg_id=""
    
    @commands.Cog.listener()
    async def on_message(self, message):
        if (message.channel.id == 888529033405530183 and 
            message.author.id != 887542628063780864):
        
            self.sverify_index  = 1
            self.sverify_list = []
            self.sverify_list.append(self.sverify_index)
  • Related