Python中A, B = C赋值语法解析:以conn, address = s.accept()为例
s.accept() Assignment Hey there! Let's demystify that conn, address = s.accept() line you're seeing in Python network programming—this is a core Python feature called tuple unpacking, and it's super useful for cleanly handling functions that return multiple values.
First, let's break down what's happening under the hood:
- When you call
s.accept(), the function returns a two-element tuple that looks something like(connected_socket, client_address). The first element is a new socket object you can use to send/receive data with the client, and the second is a sub-tuple containing the client's IP address and port number (e.g.,('127.0.0.1', 54321)).
The conn, address = ... syntax is Python's way of taking that tuple and splitting its elements directly into separate variables. Here's a simpler, non-networking example to make the logic click:
# Create a tuple with two values my_tuple = ("apple", 42) # Unpack the tuple into two variables fruit, number = my_tuple print(fruit) # Output: apple print(number) # Output: 42
In your network code, it's exactly the same idea:
conngets assigned the first element of the tuple returned bys.accept()(the active connection socket)addressgets assigned the second element (the client's address details)
Quick note on the type(conn, address) part you mentioned: that's actually a syntax error! The type() function only takes one object as its main argument. If you want to verify the type of what s.accept() returns, run this instead:
result = s.accept() print(type(result)) # Will output <class 'tuple'>
One extra tidbit: tuple unpacking isn't limited to tuples alone—Python lets you unpack any iterable (like lists, strings, or even custom objects) into variables this way. But in the case of s.accept(), the return value is specifically a tuple, so this syntax fits perfectly.
Hope that clears up the confusion!
内容的提问来源于stack exchange,提问作者Ollie Pugh

