Search code examples
pythontranscrypt

Transcrypt: How to check for empty list?


This a simple python program which causes an endless loop when compiled with Transcrypt 3.7.5:

stack = [ch for ch in "Hello"]
while stack:
    print(stack.pop())

This can be solved by replacing while stack: with while len(stack): but this would only be an unacceptable workaround. Is there any other Transcrypt-related pragma switch to get around it?


Solution

  • Use a pragma to switch on truthyness:

    http://www.transcrypt.org/docs/html/special_facilities.html#automatic-conversion-to-truth-value-pragma-tconv-and-pragma-notconv

    # __pragma__ ('tconv')
    
    stack = [ch for ch in "Hello"]
    while stack:
        print(stack.pop())
    

    This will print:

    o
    l
    l
    e
    H
    

    You can also use the -t or --tconv command line switch, as documented in:

    http://www.transcrypt.org/docs/html/installation_use.html#available-command-line-switches

    Transcrypt aims at supporting 90% of CPython by default and an additional 9% as options through pragma's and command line switches.

    The idea is that compiling with defaults gives you fast and compact code and that some mechanisms that are expensive to support via JavaScript can be activated as options. This e.g. holds for operator overloading.

    See also:

    http://www.transcrypt.org/docs/html/what_why.html#what-is-transcrypt

    and

    http://www.transcrypt.org/docs/html/differences_cpython.html

    There are fully conformant browser Pythons, e.g. PyPyJS:

    https://pypyjs.org/

    However a page using this takes a very long time to load, which for our needs was unacceptable as we use this for production in real life projects. In general, if you are going to use this professionally, it's worth while reading the docs. I must say I rarely read any documentation myself, but in this case it pays off.