Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is push! implemented correctly? #118

Open
torfjelde opened this issue Sep 25, 2024 · 3 comments
Open

Is push! implemented correctly? #118

torfjelde opened this issue Sep 25, 2024 · 3 comments

Comments

@torfjelde
Copy link

I just recently discovered that push! is implemented for Dict and it states the following in the docstring:

Because of this I sort of (maybe naively) expected push!(::OrderedDict, ::Pair) to always insert entries at the end, but this doesn't seem to be the case:

julia> using OrderedCollections

julia> d = OrderedDict(:x => 1)
OrderedDict{Symbol, Int64} with 1 entry:
  :x => 1

julia> push!(d, :y => 2)
OrderedDict{Symbol, Int64} with 2 entries:
  :x => 1
  :y => 2

julia> push!(d, :x => 3)  # Expected `:x => 3` to be after `:y => 2` here
OrderedDict{Symbol, Int64} with 2 entries:
  :x => 3
  :y => 2

Is this intentional?

@timholy
Copy link
Member

timholy commented Sep 25, 2024

Presumably this is only an issue with pre-existing keys. To me, it's not entirely obvious what the right answer is. Anyone else have any thoughts?

For reference, Python now guarantees that their dicts are ordered and here's what they do:

>>> d = {'x':1, 'y':2}
>>> d.
d.clear(       d.fromkeys(    d.items(       d.pop(         d.setdefault(  d.values(
d.copy(        d.get(         d.keys(        d.popitem(     d.update(
>>> d['x'] = 3
>>> d
{'x': 3, 'y': 2}

They don't have the analog of push!, but in Julia push!(d, k => v) is (currently) equivalent to d[k] = v.

@torfjelde
Copy link
Author

Presumably this is only an issue with pre-existing keys. To me, it's not entirely obvious what the right answer is. Anyone else have any thoughts?

Exactly; I'm also not certain what's "correct" here.

I was somewhat surprised to find that push! was even implemented for AbstractDict, as I usually associate push! with the action of "pushing onto a stack", i.e. not making that much sense in the case of containers without ordering 🤷

@timholy
Copy link
Member

timholy commented Sep 25, 2024

It's basically to support adding k/v pairs without needing to destructure the pair. But if your mental model of push! is "to the end" then it's indeed confusing.

On balance I lean towards thinking the current behavior is consistent, but it would be fine to leave this open and see if anyone else chimes in.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants