Why can I unpack a #Python set when sets are unordered?
https://stackoverflow.com/q/78931736/865169
[#]computerscience
=> More informations about this toot | More toots from arildsen@fosstodon.org
@arildsen
Because sets are iterable. And they are iterable because you want the "for" loop to work with sets. It's quite often useful to iterate over all the values in set, even if the order is not guaranteed.
=> More informations about this toot | More toots from orsinium@fosstodon.org
@orsinium I can see how it's useful to be able to iterate them. I guess it means I have to be careful with unpacking them. I find it difficult to imagine a situation where I can use variables unpacked from elements of a set for something 🤔
=> More informations about this toot | More toots from arildsen@fosstodon.org
@arildsen
Unpacking is in general not that often used, TBH. In case of sets, it's one of several ways to get a value from a single-value set and ensure along the way that there is exactly one value:
first, = some_set
=> More informations about this toot | More toots from orsinium@fosstodon.org
@orsinium I often use unpacking when returning multiple values from a function. But then again, I would never use a set for that.
=> More informations about this toot | More toots from arildsen@fosstodon.org
@arildsen
Returning multiple values from a function is a code smell. I advise people to either split the function in two separate functions or to return a dataclass, giving each return value an explicit name. Depends on cohesion.
=> More informations about this toot | More toots from orsinium@fosstodon.org
@orsinium hmm, it seems I stand corrected. What if a function's computations of two different things are tightly intertwined and you need both things? Then splitting it into two functions would necessitate repeating much of the functionality in both functions - not really good practice IMO. I guess in that case you would argue for the structured output (dataclass)?
=> More informations about this toot | More toots from arildsen@fosstodon.org
@arildsen
Yes. Or they need to be split on more than 2 functions. I don't think I ever used tuple return in Python in my 10 year career, it's just how my brain works. So, it's certainly possible :)
Interestingly, I use tuples and unpacking all the time in Go, Rust, And Elixir.
=> More informations about this toot | More toots from orsinium@fosstodon.org This content has been proxied by September (3851b).Proxy Information
text/gemini