PythonNameError: name 'discovery' is not defined

1.2k views Asked by At

Have this below function.But getting error ..any thoughts ?

def zabbix_discovery(pingdom_data):
        discovery = []
        for k,v in data["recipes"].items():
                discovery.append(
                         {"{#NAME}": str(v['name'])}
                         )
cmd_args = [
        'zabbix_sender',
        '-z', config.get('ZABBIX', 'server'),
        '-p', config.get('ZABBIX', 'port'),
        '-s', config.get('ZABBIX', 'host'),
        '-k', config.get('ZABBIX', 'key1'),
        '-o', "'{ \"data\": " + discovery + " }'"
        ]
zabbix_trapper(cmd_args)

=====

Traceback (most recent call last):
  File "txncheck_backup.py", line 52, in <module>
    '-o', "'{ \"data\": " + discovery + " }'"
NameError: name 'discovery' is not defined

=====

2

There are 2 answers

0
Cyphall On

You are using discovery before it is declared on the function call.

Also, as you declare it in the function, it will be destroyed at the end of it and wont be available in the main scope.

0
PonasM On

You are trying to access it before you call the function zabbix_discovery which assigns value to it. Even if you did correct this logical mistake, you still would not be able to access the discovery variable because it is a local variable. You can either add return discovery to the end of the function and then discovery = zabbix_discovery(pingdom_data), or make it a global variable. Former would look somewhat like this:

discovery = []
def zabbix_discovery(pingdom_data):
    global discovery
    do what you want to do with it
zabbix_discovery(args)

Also even when you fix these things your code will throw another error because you are trying to access dictionary data in your function, which has no value assigned too. If it is assigned somewhere outside the function, you can easily fix that by adding global data in the beginning of your function.

And why do you have pingdom_data as an argument in your function if you don't use it anywhere?