On Thu, Jul 12, 2018 at 10:13 AM, Gregory P. Smith <g...@krypto.org> wrote: > > On Wed, Jul 11, 2018 at 4:45 PM Jelle Zijlstra <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 https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/