Created
February 28, 2022 17:52
-
-
Save declaresub/e353609c3fdb99e7000d439814c0a726 to your computer and use it in GitHub Desktop.
Create Python tuple with assignment expression
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The following example demonstrates a use of a Python assignment expression in the course of parsing a str into a tuple. | |
# The value kid contains a key type and a key lookup id, delimited by '-'. The goal is to split them apart and | |
# convert the key lookup id to int, with little regard for readability. | |
kid = 'pwid-43' | |
key_type, key_sn = ((x:=kid.split('-'))[0], int(x[1])) | |
# To limit the scope of the variable to the expression, one can wrap the expression into a lambda function. | |
key_type, key_sn = (lambda kid: ((x:=kid.split('-'))[0], int(x[1])))(kid) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment