Skip to content

Do more work to prevent iterator invalidation for Dict's? #11316

Open
@johnmyleswhite

Description

@johnmyleswhite

Should we try to do more to prevent iterator invalidation for Dict's (and possibly for other types as well)?

Contrast this Julia code:

  _       _ _(_)_     |  A fresh approach to technical computing
  (_)     | (_) (_)    |  Documentation: http://docs.julialang.org
   _ _   _| |_  __ _   |  Type "help()" for help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 0.4.0-dev+4878 (2015-05-17 18:08 UTC)
 _/ |\__'_|_|_|\__'_|  |  Commit b3116d4 (0 days old master)
|__/                   |  x86_64-apple-darwin14.3.0

julia> x = Dict("a" => 1, "b" => 2)
Dict{ASCIIString,Int64} with 2 entries:
  "b" => 2
  "a" => 1

julia> for (k, v) in x
           println((k, v))
           delete!(x, "a")
       end
("b",2)
ERROR: UndefRefError: access to undefined reference
 in next at dict.jl:721
 in anonymous at no file

with this Python code:

Python 2.7.9 |Anaconda 1.8.0 (x86_64)| (default, Dec 15 2014, 10:37:34) 
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://binstar.org
>>> x = {"a": 1, "b": 2}
>>> 
>>> for k, v in x.iteritems():
...     print((k, v))
...     del x["b"]
... 
('a', 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
>>> 

I would argue that Python's error is more helpful for debugging, although producing such an error requires making the iteration protocol do more run-time checking on every iteration to see whether the iterator has been invalidated.

Was this a conscious decision already made for the language? Skipping these kinds of checks does feel like the Julian way, but I wanted to confirm that this was intended behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    designDesign of APIs or of the language itselfspeculativeWhether the change will be implemented is speculative

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions