Krilion
Krilion

Reputation: 37

Python: Using try/except in function and return value to list

I have a small function to loop a list of ipaddresses and do a dns lookup on them.

def lookup(addr): 
try:
    x = socket.gethostbyaddr(addr) 
    return

except socket.herror:
    x = addr 
    print  (addr, "not found") 
    return None  

However insted of just printing the ipaddresses with missing dns record i want to save them to a list. But when i try to return a value on the socket.herror i get "NameError: name 'missing' is not defined" when trying to access it in anyway.

def lookup(addr): 
try:
    x = socket.gethostbyaddr(addr) 
    return

except socket.herror:
    x = addr 
    print  (addr, "not found") 
    return missing  

I have not really find a similar example of this type of function so maybe i have missunderstod the use of try/except?

Upvotes: 0

Views: 395

Answers (1)

Lost
Lost

Reputation: 1008

You are never defining "missing" as a variable before trying to return it.The other issue you have is that you are trying to return nothing or return something, so you'll have to build logic on the outside that isn't included here to make it work.

Consider this (similar) approach which takes the whole input list and just returns a list with the missing addresses:

def find_missing(addr_list): 
    missing = []
    for addr in addr_list:
        try:
            x = socket.gethostbyaddr(addr) 

        except socket.herror:
            missing.append(addr)
    return missing

Upvotes: 2

Related Questions