Search code examples
pythonvariable-assignmentiterable-unpackingshorthandpython-typing

unpack to int and string in python


Is there a way to unpack to diferent types? this is the case:

# data = [4, "lorem", "ipsum", "dolor", "sit", "amet"]
(parts, *words) = data

data is provided. I never assign this value. I add as example. parts must be an int, all the rest of the list is assigned as list of strings.

The only way that I have found is reassign the variable parts as next:

(parts, *words) = [4, "lorem", "ipsum", "dolor", "sit", "amet"]
parts = int(parts)

but I don't like repeat asignment variable twice in a row. Since python is a language that keeps clean and simple I'm looking a solution.

*edit: Let me know if is a valid practice reassign twice in a row.


Solution

  • In Python's static typing annotations, lists (and all sequences aside from tuples) are assumed to be of homogeneous type (which may still be a union of multiple types, but it's not a different single type depending on which index you're looking at). Your list is violating that assumption by having index 0 have one type, while the other indices have a different type. Even though Python in general doesn't enforce the "intended" usage of list, type checkers do, and there's no mechanism to work around that shy of manual casts or type conversions, as you're doing here.

    Short answer: You're "misusing" lists, and typing won't help you when you do that. So either ignore/disable the type-checker for this code (it'll work just fine after all), or live with a pointless cast.