Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python socket progran
#1
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
Reply
#2
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/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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Socket creation speed difference Python 2.7 / Python 3.7 PiAil 1 2,461 Feb-13-2019, 01:55 PM
Last Post: PiAil
  Multithreading socket in Python. I'm missing something Guybrush 1 3,977 Apr-28-2017, 11:14 PM
Last Post: Ofnuts

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020