{1,2,7}.freeze() or {1,2,7}.to_frozenset() seem very natural and if this can be optimized to avoid the copy, it's perfect. For bytearray, one use case would be to optimise bytearray([1,2,7,2]) in something like [1,2,7,2].to_byterray(). About bytes, one could have (1,2,7,2).to_bytes() instead of bytes((1,2,7,2)) because b'\x01\x02\x07\x02' is long and boring. What about variables in the values {1,2,x}.freeze() should work too ? bytes((1,2,7,x)) is not writable as a b string and creates a copy.
Le jeu. 12 juil. 2018 à 02:24, Chris Angelico <ros...@gmail.com<mailto:ros...@gmail.com>> a écrit : On Thu, Jul 12, 2018 at 10:13 AM, Gregory P. Smith <g...@krypto.org<mailto:g...@krypto.org>> wrote: > > On Wed, Jul 11, 2018 at 4:45 PM Jelle Zijlstra > <jelle.zijls...@gmail.com<mailto:jelle.zijls...@gmail.com>> > wrote: >> This could be done safely and without too much craziness if .freeze() on a >> set returned a new frozenset. The compiler could then safely optimize {a, >> set, literal}.freeze() into a frozenset literal, because methods on builtin >> types cannot be monkeypatched. There's been talk of a similar optimization >> on calls to .format() on string literals (not sure whether it's been >> implemented). >> >> Whether implementing that is a good use of anyone's time is a different >> question. > > > Neat optimization. I hadn't considered that. We do know for sure it is a > builtin type at that point. > > If that were implemented, bytes objects could gain a to_bytearray() (along > the lines of the int.to_bytes() API) method that could be optimized away in > literal circumstances. Be careful: a bytearray is mutable, so this isn't open to very many optimizations. A .freeze() method on sets would allow a set display to become a frozenset "literal", stored as a constant on the corresponding function object, the way a tuple is; but that's safe because the frozenset doesn't need to concern itself with identity, only value. Example: def f(x): a = (1, 2, 3) # can be optimized b = (x, 4, 5) # cannot c = [6, 7, 8] # cannot Disassemble this or look at f.__code__.co_consts and you'll see (1, 2, 3) as a single constant; but the others have to be built. +1 on set.freeze(); +0 on bytes.to_bytearray(). ChrisA _______________________________________________ Python-ideas mailing list Python-ideas@python.org<mailto:Python-ideas@python.org> https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/