[Python-ideas] .pyu nicode syntax symbols (was Re: Empty set, Empty dict)

Chris Angelico rosuav at gmail.com
Sat Jun 28 07:28:57 CEST 2014


On Sat, Jun 28, 2014 at 3:00 PM,  <random832 at fastmail.us> wrote:
> On Sun, Jun 22, 2014, at 16:18, Terry Reedy wrote:
>
>> 2. Write pyu.py. It should first translate x.pyu to the equivalent x.py.
>
> What is the equivalent x.py for "BUILD_SET 0" rather than "LOAD_GLOBAL
> (set), CALL_FUNCTION 0"?

Is there any reason that it has to be normal-looking source code?

def empty_set_literal(): # line 123 of somefile.pyu
    print("I'm an empty set!", ∅)

# becomes
empty_set_literal =
type(lambda:0)(type((lambda:0).__code__)(0,0,0,3,67,b't\x00\x00d\x01\x00h\x00\x00\x83\x02\x00\x01d\x00\x00S',(None,"I'm
an empty set!",{}),('print',),(),"somefile.pyu","empty_set_literal",123,b"\x00\x01"),globals(),"empty_set_literal")

I got most of the args for the code() constructor by disassembling the
function, using a one-element set, and then manually edited the code
afterward. It does appear to work:

>>> dis.dis(empty_set_literal)
124           0 LOAD_GLOBAL              0 (print)
              3 LOAD_CONST               1 ("I'm an empty set!")
              6 BUILD_SET                0
              9 CALL_FUNCTION            2 (2 positional, 0 keyword pair)
             12 POP_TOP
             13 LOAD_CONST               0 (None)
             16 RETURN_VALUE
>>> empty_set_literal()
I'm an empty set! set()

Given that the purpose of this is to make something executable, not
something readable (in contrast to, say, 2to3), I don't think it would
be a problem to have nightmare-level code in there occasionally. That
said, I'm not particularly in favour of the proposal - I just felt
like answering this part of it :)

ChrisA


More information about the Python-ideas mailing list