0

In the function main I have

def main():
    #...
    def button_callback(button,a, byMouse,label):
            #...
            date = date - oneday
            while(date.isoweekday()>5): date = date -oneday
            #...
    oneday = datetime.timedelta(1)
    date = datetime.date.today()

python complains: local variable 'date' referenced before assignment, which is expected. In other parts of main() I pay attention not to assign but to modify, thus I have for example

def main():
    # other part of main()
    def clear_callback( button,byMouse,aaa):
        a_cats.clear()

    a_cats = set(["GT","GR"])

which python is happy about (it woudn't be if I set e.g. a_cats = a_cats.clear() ).

Is there a way to modify a datetime object without explicitly using "=", so that I can avoid using global variables ?

2 Answers2

2

If you're using Python 3.x, you can declare the variable as nonlocal:

def main():
    def button_callback(button,a, byMouse,label):
        nonlocal date  # <--------------
        date = date - oneday
        ...

    oneday = datetime.timedelta(1)
    date = datetime.date.today()
falsetru
  • 357,413
  • 63
  • 732
  • 636
0

datetime object is immutable. The only way to change date is to bind it to a new datetime object.

To assign to outer-scope variable, you could use nonlocal in Python 3 as @falsetru suggested or emulate it using a list or a custom object in Python 2:

def button_callback(self, *args):
    self.date -= DAY

See What limitations have closures in Python compared to language X closures?

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670