
On Mon, Jan 17, 2022 at 7:12 PM Paul Moore <p.f.moore@gmail.com> wrote:
On Mon, 17 Jan 2022 at 01:11, Chris Angelico <rosuav@gmail.com> wrote:
On Mon, Jan 17, 2022 at 10:14 AM Paul Moore <p.f.moore@gmail.com> wrote:
On Sun, 16 Jan 2022 at 22:55, Steven D'Aprano <steve@pearwood.info> wrote:
> def f(): ... return frozenset({1, 2, 3}) ... > a = f.__code__.co_consts[1] > a frozenset({1, 2, 3}) > b = f() > assert a == b > a is b False
Each time you call the function, you get a distinct frozenset object.
I may just be reiterating your point here (if I am, I'm sorry - I'm not completely sure), but isn't that required by the definition of the frozenset function. You're calling frozenset(), which is defined to "Return a new frozenset object, optionally with elements taken from iterable". The iterable is the (non-frozen) set {1, 2, 3}.
Where is that definition?
https://docs.python.org/3/library/functions.html#func-frozenset
According to help(frozenset), it will "[b]uild an immutable unordered collection of unique elements", so it doesn't necessarily have to be a brand new object.
I'd read "build" as meaning it is a new object. But regardless, I view the language documentation as authoritative here.
That should probably be corrected, then.
With mutables, it does have to return a new one every time (list(x) will give you a shallow copy of x even if it's already a list), but with immutables, it's okay to return the same one (str and tuple will return self).
That's an optimisation, not a guarantee, so while it's relevant, it's not sufficient (IMO).
Hmm, not sure whether it's a guarantee or not. It's certainly a very obvious optimization. ChrisA