Optimising constant expressions

Rob Cliffe via Python-list <[email protected]>
Newsgroups gmane.comp.python.general
Message-ID <[email protected]>
I am using Python 3.13.3 on Windows 11.
I notice that the compiler can optimise (some) constant expressions 
containing operators plus numbers or strings, e.g.
     2+2 is compiled as 4
     1 + (2.5 + 3+4j) is compiled as 6.5+4j
     'a' + 'b' is compiled as 'ab'
     and even 'a'*4096 is compiled as a single long string, but 'a'*4097 
isn't (a line must be drawn somewhere).  YMMV.
This is safe because str, int etc. are built-in types and can not be 
monkey-patched (at least, not easily; it's beyond my ability 🙂).
Question 1:
     Couldn't this be done with expressions involving *methods* of 
strings or numbers, e.g. couldn't
         (15).bit_count() be compiled as 4
         'a b c'.split() be compiled as ['a', 'b', 'c']
     Is there are reason why this is unsafe?
     Is it avoided for possible future compatibility issues?
     Is it too difficult?
     Would it slow down the compiler too much?
Question 2:
     Couldn't this be done (or is it to some extent already done) with 
other-built-in types, e.g. couldn't
         [1] + [2] be compiled as [1,2]
Best wishes
Rob Cliffe
-- 
https://mail.python.org/mailman3//lists/python-list.python.org
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.