Another question does not explain why I can't change variable time_verf without using 'global' in the example (2) but still can do it to the list in the example (4).
On the resource I found that I can not change global variable from within a function, which is clearly illustrated by these examples:
from datetime import datetime, timedelta
time_verf = datetime.now()
I think I understand why the following is working (1):
def check_global():
global time_verf
clean_list = time_verf + timedelta(hours=12) # время очистки листа
if clean_list < datetime.now():
list_verf.clear()
time_verf = datetime.now()
print('ok')
>> check_global()
<< ok
Next it throws exception when I comment out line with global keyword (2):
def check_global():
# global time_verf
clean_list = time_verf + timedelta(hours=12) # время очистки листа
if clean_list < datetime.now():
list_verf.clear()
time_verf = datetime.now()
print('ok')
>> check_global()
<< Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 3, in check_global
UnboundLocalError: local variable 'time_verf' referenced before assignment
And then again can be again referenced without 'global' when line with assignment commented out(3):
def check_global():
# global time_verf
clean_list = time_verf + timedelta(hours=12) # время очистки листа
if clean_list < datetime.now():
list_verf.clear()
# time_verf = datetime.now()
print('ok')
>> check_global()
<< ok
But why am I allowed to update list defined in the outer scope without using global (4)?
list = []
def check_global_list():
list.append('check')
>> check_global_list()
>> list
<< ['check']