in the following function, what is making try: exit early? If I put the same code outside a def block it works fine.
tiles = ['095D', '094M']
in_file = 'in_file'
out_file = 'out_file'
expression = ''' "FIELDNAME" LIKE 'STUFF' '''
def foobar(in_file, out_file, expression):
print in_file, out_file, expression
try:
print 'this is trying'
#pretty print tile list, from http://stackoverflow.com/questions/2399112/python-print-delimited-list
tiles = ','.join(map(str,tiles))
print 'made it past tiles!'
print 'From %s \nselecting %s \ninto %s' % (in_file, tiles, out_file)
except:
print 'Made it to the except block!'
foobar(in_file, out_file, expression)
Results:
D:\> python xx-debug.py
in_file out_file "FIELDNAME" LIKE 'STUFF'
this is trying
Made it to the except block!
Results with the same code not in a def:
this is trying
made it past tiles!
From in_file
selecting 095D,094M
into out_file
The reason it’s not working is because you defined
tilesin the global scope. In the function you’re assigning totiles. This makestilesa local scoped name in the function. This, in turn, means that the code in the function won’t look fortilesin the global scope at all.In the assignment, you’re trying to get
tiles(this is before it has been assigned locally.) This results in an exception being raised, since you tried to access an unassigned local variable.The quick fix is to use
global:As others said, don’t just catch exceptions without doing something with them. When debugging code, you want exceptions to be thrown so you can find and fix the cause! Either remove the
try…except, or make theexcepttake an exception and print useful information about it, like this:This may be a lot to read, but you will understand Python much better if you do read it:
http://docs.python.org/reference/executionmodel.html
It explains how Python handles variable definitions in the module scope and function scopes, etc. It also covers exceptions.