Strange compiler warning
Peter Hansen
peter at engcorp.com
Mon Oct 7 20:33:31 EDT 2002
Robin Becker wrote:
> with 2.2.1 I get the message
>
> SyntaxWarning: name '_dbg' is assigned to before global declaration with
> the following code, but things seem to be working, so is the compiler
> wrong or too lazy to see the globals on all paths? How should one do
> this sort of on the fly local debugging?
>
> ......
> if not globals().has_key('_dbg'):
> global _dbg
> _dbg=open('/tmp/_dbg.txt','w')
> else:
> global _dbg
> print >>_dbg,'=======================\n' + text
It's a little unclear what you want, but this looks better:
global _dbg
try:
_dbg
except NameError:
_dbg = open('/tmp/_dbg.txt', 'w')
print >>_dbg, '=====\n' + text
Basically:
1. the "global" statement applies for the following scope of the
function, so you need only one,
2. you can check if it exists simply by trying to reference it,
3. using exceptions is generally better than not.
But what are you really trying to accomplish?
-Peter
More information about the Python-list
mailing list