Python Forum
Python socket progran - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Python socket progran (/thread-4097.html)



Python socket progran - Taimoor - Jul-22-2017

i don't understand this code.what is happening where does socket and a come from.What means by a.startswith?
how does python understands arguments within square brackets like from the function defined below:
get_protnumber('AF_')[2]
the result is AF_INET
i will be grateful if someone guides me step by step
import socket
def get_protnumber(prefix):
 return dict( (getattr(socket, a), a)
   for a in dir(socket)
     if a.startswith(prefix))

proto_fam = get_protnumber('AF_')
types = get_protnumber('SOCK_')
protocols = get_protnumber('IPROTO_')

for res in socket.getaddrinfo('www.thapar.edu', 'http'):
 family, socktype, proto, canonname, sockaddr = res

print 'Family         :', proto_fam[family]
print 'Type           :', types[socktype]
print 'Protocol       :', protocols[proto]
print 'Canonical name :', canonname
print 'Socket address :', sockaddr



RE: Python socket progran - MTVDNA - Jul-24-2017

There's a lot happening in these two lines of code:

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])
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.
So
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/stdtypes.html#str.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.