3

I have a python program that run in loop to count the number of keys in bucket, it works fine when It has one or more keys. It throws an error when it has 0 objects.

def CdmCount(Destbucket):
    global key
    totalcdms = 0
    for key in Destbucket.get_all_keys():
        totalcdms += 1
        print totalcdms
    assert isinstance (key,object )
    return (totalcdms, key)

I see following error:

  File "check_fun.py", line 24, in CdmCount
  return (totalcdms, key)
NameError: global name 'key' is not defined

Complete code http://pastebin.com/QrAwL4Dq

Update:

After I add a upper level boto function to list the number of keys exist, if its zero exit.

    keys = list(Destbucket.list())
if not keys:
    print "List is empty"
    sys.exit(2)

Is it a good approach?

Forge
  • 6,538
  • 6
  • 44
  • 64
Chucks
  • 899
  • 3
  • 13
  • 29

1 Answers1

0

Your code has reached the assert statement while a value was yet to assigned to key therefore it is not defined. Not using a global variable here would have also trigger an error (UnboundLocalError: local variable 'key' referenced before assignment).

Using a global variable doesn't seem justified here, you should consider using function return values instead.

Also, it's bad practice to use multiple variables with the same name. In this case you are defining global key and then re-defining key again to be the iterating variable in the loop. Something like this would be better:

global key
for k in keys:
    if some_condition == k:
        key = k
...
Forge
  • 6,538
  • 6
  • 44
  • 64