I
I
igreklpofrss2021-12-04 14:45:31
Python
igreklpofrss, 2021-12-04 14:45:31

Why is global not global?

I am writing a telegram bot. Here is the code how it works:

global spisok
spisok = []
values = []

@bot.message_handler(func = lambda c: True, commands=['komanda'])
def 1_step(message):
    'тут код продолжается'
    for i in values:
        spisok.append(i)
    'тут код продолжается'
    bot.register_next_step_handler(msg, 2_step)

def 2_step(message):
     'тут код продолжается'
    bot.register_next_step_handler(msg, 3_step)

def 3_step(message):
     'тут код продолжается'
    bot.register_next_step_handler(msg, 4_step)

def 4_step(message):
     'тут код продолжается'
     print(spisok)

UnboundLocalError: local variable 'spisok' referenced before assignment

spisok is set as a global variable at the very beginning of the code. All code is written the way I use it. The first step adds values ​​to this list. I need to use this list in step 4, but the console gives an error that the variable is local and not set, although this should not be. What is written wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
gimntut, 2021-12-04
@igreklpofrss

You put the directive in the wrong place. It should be like this:

spisok = []

def 1_step(message):
  global spisok
  spisok.append(...)

D
Denis Kulikov, 2021-12-04
@Artin24

I agree with those who above
global spisok
need to write directly in all methods in which you change the contents of the list. And really, learn Python.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question