Ramin Honary on Nostr: Beware: #Python (today I learned) If you accidentally put a comma at the end of a ...
Beware: #Python (today I learned)
If you accidentally put a comma at the end of a return statement, a 1-tuple is returned:
def thing(x):
return x+1,
Running thing(3) returns (4,) instead of just 4. When you think about it how Python implements multiple returns values as tuples, and that assigning multiple comma-separated values does not require values be enclosed in parentheses, it makes sense that this would be the case with Python syntax. But even so, it still caught me off guard, I would have expected a syntax error.
Published at
2023-12-23 16:46:28Event JSON
{
"id": "79cc2f5b5331e7168c18f05c6e9845cd9fa8b82f2d0a2611015b286b168c809a",
"pubkey": "4ae97b2084e2b2c3bc17385ca42179c75c9177c2fef6f0b99c65fa177ff4d1fa",
"created_at": 1703349988,
"kind": 1,
"tags": [
[
"t",
"python"
],
[
"proxy",
"https://emacs.ch/users/ramin_hal9001/statuses/111630744856508252",
"activitypub"
]
],
"content": "Beware: #Python (today I learned)\nIf you accidentally put a comma at the end of a return statement, a 1-tuple is returned:\ndef thing(x):\n return x+1,\nRunning thing(3) returns (4,) instead of just 4. When you think about it how Python implements multiple returns values as tuples, and that assigning multiple comma-separated values does not require values be enclosed in parentheses, it makes sense that this would be the case with Python syntax. But even so, it still caught me off guard, I would have expected a syntax error.",
"sig": "3732d5ff32f89d9484e27323d8e1eee91a8254b0ed442e8d082070ef7be5209abc31b7a79a126082c129f08144a507182a3bc1e421fe0bdfdf194c89b02d51d9"
}