Search code examples
pythonpython-3.ximaplib

Variable scope inside for loop (imaplib library documentation)


import getpass, imaplib

M = imaplib.IMAP4()
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    print('Message %s\n%s\n' % (num, data[0][1]))
M.close()
M.logout()

The code is picked up from documentation here (scroll to the bottom of the page). I think that data assignment inside the for loop overwrites the data assignment made just before the for loop starts. Since scope in python is at nearest function, class or module; data variable assignment will override the original assignment.

So the data used by the for loop is actually the one which was set inside the for loop when the loop ran 1st time. Is this a bug in the code and should the inner variable be renamed to say data1?


Solution

  • I think it is OK but not readable enough maybe, or make it clearer you can rename it to data1

    The problem is that data[0].split() returns a new object and here for loop is using that anonymous object which won't be overwritten by the inner assignment.