问题
I'm trying to do something that seems very simple, and falls within the range of standard python. The following function takes a collection of sets, and returns all of the items that are contained in two or more sets.
To do this, while the collection of sets is not empty, it simply pops one set out of the collection, intersects it with the remaining sets, and updates a set of items that fall in one of these intersections.
def cross_intersections(sets):
in_two = set()
sets_copy = copy(sets)
while sets_copy:
comp = sets_copy.pop()
for each in sets_copy:
new = comp & each
print new, # Print statements to show that these references exist
print in_two
in_two |= new #This is where the error occurs in IronPython
return in_two
Above is the function I'm using. To test it, in CPython, the following works:
>>> a = set([1,2,3,4])
>>> b = set([3,4,5,6])
>>> c = set([2,4,6,8])
>>> cross = cross_intersections([a,b,c])
set([2, 4]) set([])
set([4, 6]) set([2, 4])
set([3, 4]) set([2, 4, 6])
>>> cross
set([2, 3, 4, 6])
However, when I try to use IronPython:
>>> b = cross_intersections([a,b,c])
set([2, 4]) set([])
set([4, 6]) set([2, 4])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:/path/to/code.py", line 10, in cross_intersections
SystemError: Object reference not set to an instance of an object.
In the title I said this was a mysterious null pointer exception. I probably have no idea how .NET handles null pointers (I've never worked with a C-like language, and have only been using IronPython for a month or so), but if my understanding is correct, it occurs when you attempt to access some property of an object that points to null
.
In this case, the error occurs at line 10 of my function: in_two |= new
. However, I've put print
statements right before this line that (at least to me) indicate that neither of these objects point to null
.
Where am I going wrong?
回答1:
It's a bug. It will be fixed in 2.7.1, but I don't think the fix is in the 2.7.1 Beta 1 release.
回答2:
This is a bug still present in the 2.7.1 Beta 1 release.
It has been fixed in master, and the fix will be included in the next release.
IronPython 3.0 (3.0.0.0) on .NET 4.0.30319.235
Type "help", "copyright", "credits" or "license" for more information.
>>> import copy
>>>
>>> def cross_intersections(sets):
... in_two = set()
... sets_copy = copy.copy(sets)
... while sets_copy:
... comp = sets_copy.pop()
... for each in sets_copy:
... new = comp & each
... print new, # Print statements to show that these references exist
... print in_two
... in_two |= new # This is where the error occurs in IronPython
... return in_two
...
>>>
>>> a = set([1,2,3,4])
>>> b = set([3,4,5,6])
>>> c = set([2,4,6,8])
>>>
>>> cross = cross_intersections([a,b,c])
set([2, 4]) set([])
set([4, 6]) set([2, 4])
set([3, 4]) set([2, 4, 6])
来源:https://stackoverflow.com/questions/6712051/ironpython-function-works-in-cpython-mysterious-null-pointer-exception-in-iron