[Tutor] Globals?
Kent Johnson
kent37 at tds.net
Fri Nov 12 16:02:07 CET 2004
Liam,
When you make any assignment to a variable inside a function, Python
assumes that the variable is local to the function. Then any use of the
variable before it's first assignment is an error.
To force a variable in a function to be global, put a 'global' statement
in the function. You need to add
global badConnectCycle
to your function getReturns
If you don't make any assignment to a variable, then the global (module)
namespace is searched. That is why badUserList works fine - you never
assign it, you just access the list methods.
Kent
Liam Clarke wrote:
> Hi all,
>
> Having trouble with something, it is 3:30am in the morning, so this
> may be a dumb problem, if so, I apologise.
>
> In my prog, there's two variables created right at the get go -
>
> import imaplib
> import email.Parser
> import os
> import os.path
> import datetime
> import md5
> from pause import *
>
> badUserList=[]
> badConnectCycle=0
>
> as I want them to be global within this module, so that another module
> can pick them out easily.
>
> Now, I just added badConnectCycle, badUserList has been there awhile,
> and it's used in
>
> the function connectToImap which is called by getReturns which is
> called by main(), and my other module can get it no problem, so
> badUserList is fine.
>
> badConnectCycle... is giving me errors -
>
> badConnectCycle is used in getReturns, as so -
>
> if session == "NoConnect" :
> badConnectCycle += 1
> continue
>
>
> function getReturns ends as follows -
>
> if badConnectCycle == len(user) and badConnectCycle > 0: return ("NoConnect","")
> if badUserList and not sender: return ('NoLogin',"")
> if matchindex[0] and not sender: return ('NoNew', '')
> if not sender: return ("NoMatch","")
> return (sender, msgdata)
>
> and it's at that line
>
> if badConnectCycle == len(user) and badConnectCycle > 0:
>
> that I get this error:
>
> UnboundLocalError: local variable 'badConnectCycle' referenced before
> assignment.
>
> Which is confusing me because badUserList is used within a function
> called by getReturns, and I've had no problem with it.
>
> Help anyone? Much appreciated if you can.
>
> Regards,
>
> Liam Clarke
More information about the Tutor
mailing list