There's a lot happening in these two lines of code:
So you could read it as:
So the function returns a dictionary that it generates from the socket module. Here's what it does:
From the documentation
getattr(socket, a) gets the value for attribute a, so comparable to socket.a
(getattr(socket, a), a) makes a tuple of the value of a, and a itself. This wil serve as a key value pair for the dictionary that we are creating. Because we are looping through a bunch of attributes, we get a list of (key, value) tuples.
dict( ... ) finally turns it all into a dictionary.
This function basically does the same thing, except not in one line:
get_protnumber('AF_') returns a dictionary,
get_protnumber('AF_')[2] returns the value from that dictionary that has the key 2.
def get_protnumber(prefix): return dict( (getattr(socket, a), a) for a in dir(socket) if a.startswith(prefix))Python interprets this as two lines, because of the parentheses () of dict.
So you could read it as:
def get_protnumber(prefix): return dict( (getattr(socket, a), a) for a in dir(socket) if a.startswith(prefix) )which makes a lot more sense i.m.o.
So the function returns a dictionary that it generates from the socket module. Here's what it does:
From the documentation
Quote:dir([object])So
Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.
dir(socket)returns a list of valid attributes of the socket module.
for a in dir(socket) if a.startswith(prefix)This loops through all of socket's attributes, calling them a, but only those that start with prefix (see: https://docs.python.org/3/library/stdtyp...startswith)
getattr(socket, a) gets the value for attribute a, so comparable to socket.a
(getattr(socket, a), a) makes a tuple of the value of a, and a itself. This wil serve as a key value pair for the dictionary that we are creating. Because we are looping through a bunch of attributes, we get a list of (key, value) tuples.
dict( ... ) finally turns it all into a dictionary.
This function basically does the same thing, except not in one line:
def get_protnumber2(prefix): l = [] for attribute in dir(socket): if attribute.startswith(prefix): key = getattr(socket, attribute) value = attribute l.append((key,value)) return dict(l)Now our function returns a dictionary. To get a value from a dictionary you need to use its key:
example_dict = {'apples': 5, 'bananas': 3, 'pears': 0} print example_dict['apples']In this case the key is 2, so
get_protnumber('AF_') returns a dictionary,
get_protnumber('AF_')[2] returns the value from that dictionary that has the key 2.