Transcrypt icon indicating copy to clipboard operation
Transcrypt copied to clipboard

Problem subclassing dict: meta is undefined

Open wrpscott opened this issue 9 years ago • 2 comments

# test the subclassing of a dict. This works as expected in Cpython.
# with transcrypt, loading this into a browser with the following html file:
"""
<html>
    <head>
        <script src="__javascript__/defdcttest.js"></script>
    </head>
    <body>
        Refresh browser window to restart
    </body>
</html>
"""
# produces an error 'TypeError: meta is undefined[Learn More]' in the browser console.

class defaultdict(dict):
    def __init__(self, genfunc):
        dict.__init__(self)
        self._genfunc = genfunc

    def __getitem__(self, key):
        if key in self:
            return dict.__getitem__(self, key)
        else:
            newval = self[key] = self._genfunc()
            return newval


# taken from https://docs.python.org/3/library/collections.html#collections.defaultdict
print("hello world")
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
    d[k].append(v)
print(sorted(d.items()))

wrpscott avatar Sep 15 '17 18:09 wrpscott

Shouldn't you use s.items() ?

pmukherjeee avatar Sep 16 '17 04:09 pmukherjeee

In Transcrypt, to accommodate for fast code and seamless interoperation with JavaScript libraries, Python standard types like list, dict, int, float and string aren't full blown classes but rather enriched JavaScript types. Giving them the full Python class mechanism would have made them heavy and also would have made it impossible to interchange data with JavaScript libraries directly.

The advantage is that Transcrypt is as fast and compact as native JavaScript and can work with any JS lib without conversion. The disadvantage is that these standard types cannot be inherited from. A workaround is to wrap them in classes ("boxing", like in Java") and inherit from those.

Transcrypt's central design choices are summarized here:

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

@pmukherjeee If I'm correct, for k, v in s: should work, since s is a list, not a dictionary. To do the same with dictionaries use the iconv pragma (or, less desirable, the -i command line switch) as explained in:

http://www.transcrypt.org/docs/html/special_facilities.html#automatic-conversion-to-iterable-pragma-iconv-and-pragma-noiconv

JdeH avatar Sep 22 '17 14:09 JdeH