Support item assignment
See original GitHub issueSince OrderedSet
supports indexing, it’s natural to assume that assignments and del
would work as well, but they don’t:
>>> s = OrderedSet(['foo'])
>>> s[0]
'foo'
>>> s[0] = 'bar'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'OrderedSet' object does not support item assignment
>>> del s[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'OrderedSet' object doesn't support item deletion
There’s an easy workaround for del
(s.remove(s[0])
), but not for item assignments. As far as I can tell, there is no way to reorder items at all, so it’s impossible to replace an element with another one (while preserving its index).
Issue Analytics
- State:
- Created 2 years ago
- Comments:9 (4 by maintainers)
Top Results From Across the Web
'str' object does not support item assignment - Stack Overflow
The 'str' is an immutable data type. Therefore str type object doesn't support item assignment.
Read more >TypeError: 'str' object does not support item assignment
The Python "TypeError: 'str' object does not support item assignment" occurs when we try to modify a character in a string. Strings are...
Read more >Python 'str' object does not support item assignment solution
The “'str' object does not support item assignment” error tells you that you are trying to modify the value of an existing string....
Read more >TypeError 'str' Object Does Not Support Item Assignment - Sentry
The Problem. When you run the code below, Python will throw the runtime exception TypeError: 'str' object does not support item assignment ....
Read more >TypeError 'str' object does not support item assignment
While working with strings in Python, you might have come across the error typeerror 'str' object does not support item assignment.
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
I think the only reasonable thing to do with
__setitem__
given an existing item is to raise an error. That makes__setitem__
actually the easier case, so I can support it too.I agree with @Aran-Fey’s breakdown.
__delitem__
seems straightforward. As for__setitem__
, 2.ii and 2.iii doing anything other than raising an exception (ValueError
) would be surprising, but we can probably support 2.i without much difficulty or confusion. Since membership checking is O(1), checking if an exception must be raised for__setitem__
would be efficient.It might be simpler to not support
__setitem__
, but if nothing else we can probably move forwards with__delitem__
.