Reputation: 820
As in this question that shows how using nan from numpy causes problems with a dict, why does math.nan behave differently? (Python3)
import math
import numpy as np
d = {math.nan:'baz', math.nan:'bip' }
print(d)
e = {np.float('nan'):'foo', np.float('nan'):'bar' }
print(e)
Output
{nan: 'bip'}
{nan: 'foo', nan: 'bar'}
Upvotes: 2
Views: 104
Reputation: 362497
It's because math.nan
is a module level attribute, so you get the identical object both times. CPython dicts have a shortcut† for identity checks
>>> any(k == math.nan for k in d)
False
>>> math.nan in d
True
With np.float('nan')
you have a function call, returning different instance each time. Using Python's built-in float('nan')
would be similar again, this is not really related to numpy.
>>> np.float('nan') is np.float('nan')
False
>>> math.nan is math.nan
True
>>> float('nan') is float('nan')
False
†Lists, tuples, etc also have this. See Making an object x such that “x in [x]” returns False for more about that.
Upvotes: 3