Lichen

tests/nested_mixed_names.py

338:61776a5a0e16
2016-12-07 Paul Boddie Associate constant name information with references so that structure members such as function instance default members can be generated statically, thus eliminating unnecessary structure initialisation in the translated code. Improved the determination of dynamic functions in the importer to consider only non-constant defaults.
     1 class C:     2     def c(self):     3         return 1     4      5 class D(C):     6     def d(self):     7         return 3     8      9 a = 4    10 l = []    11     12 def f(x):    13     14     # Test global mutation.    15     16     l.append(x.c())    17     18     # Test function initialisation.    19     20     def g(y, x=x): # x must be introduced as default here    21         if y:    22             x = D()    23         return x.d(), y, a # UnboundLocalError in Python (if y is a false value)    24     25     return g    26     27 # Provide a default instance for a function to be obtained.    28     29 fn = f(C())    30 print l                     # [1]    31 print fn                    # __main__.f.$l0    32 try:    33     print fn(2)             # should fail due to g requiring an object providing d    34 except TypeError:    35     print "fn(2): fn initialised with an inappropriate object"    36     37 try:    38     print fn(0)             # should fail due to g requiring an object providing d    39 except TypeError:    40     print "fn(0): fn initialised with an inappropriate object"    41     42 # Override the default when calling the function.    43     44 print fn(2, D())            # (3, 2, 4)    45 print fn(0, D())            # (3, 0, 4)    46     47 # Provide a more suitable default instance for the function.    48     49 fn = f(D())    50 print l                     # [1, 1]    51 print fn(2)                 # (3, 2, 4)    52 print fn(0)                 # (3, 0, 4)    53 print fn(0, D())            # (3, 0, 4)    54     55 # Override with an unsuitable object even though it would be ignored.    56     57 try:    58     print fn(1, C())    59 except TypeError:    60     print "fn(1, C()): an unsuitable argument was given."    61     62 # Override with an unsuitable object.    63     64 try:    65     print fn(0, C())    66 except TypeError:    67     print "fn(0, C()): an unsuitable argument was given."