#!/usr/bin/env python # encoding: utf-8 # sample code for setattr bug # steven.samuel.cole@gmail.com from sys import modules def show_weird_behavior(): # set a local variable called name to value 'value', # equivalent to name = 'value' setattr(modules[__name__], 'name', 'value') # this code prints name : value as expected print 'name :', name # if the following line is active: # name = None # the print line above causes an # UnboundLocalError: local variable 'name' referenced before assignment # --> code executed later has an impact on code executed earlier ?!? # IMHO, this behavior is so unexpected that it qualifies as a bug # same behavior on Python 2.6.1 and 2.7 on x64 Mac Snow Leopard # and Python 2.6.5 on x64 Kubuntu 10.04 if __name__ == '__main__': show_weird_behavior()