Skip to content

Instantly share code, notes, and snippets.

@declaresub
Created February 28, 2022 17:52
Show Gist options
  • Save declaresub/e353609c3fdb99e7000d439814c0a726 to your computer and use it in GitHub Desktop.
Save declaresub/e353609c3fdb99e7000d439814c0a726 to your computer and use it in GitHub Desktop.
Create Python tuple with assignment expression
# 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