codon icon indicating copy to clipboard operation
codon copied to clipboard

NameError when handling the list comprehension.

Open xiaxinmeng opened this issue 2 years ago • 2 comments

The given example shows a list comprehension that creates a new list by applying a specific operation or function to each element of an iterable, i.e., numbers in the range of 0 to 4, inclusive. It defines a loop, i.e., for k in range(5), that iterates over the numbers 0 to 4. ((m := k+1), k * m) creates a tuple containing two elements: the value of m and the product of k and m. The list comprehension will create a list of these tuples for each value of k in the range. The expected resulting list looks like this: [(1, 0), (2, 2), (3, 6), (4, 12), (5, 20)], while Codon throws a NameError.

test.py

a = [((m := k+1), k * m) for k in range(5)]
print(a)

The expected output (CPython 3.10.8): [(1, 0), (2, 1), (3, 2), (4, 3), (5, 4)]

The actual output on Codon v 0.16.0

NameError: variable 'm' not yet defined
Raised from: __internal__.undef:0
/home/xxm/Desktop/Codon/codon-linux-x86_64/codon-deploy/lib/codon/stdlib/internal/internal.codon:368:13
Aborted (core dumped)

Reproduce step:

download the Pre-built binaries for Linux Type " codon run --release test.py" in the console.

Environment: Ubuntu 18.04 Codon v0.16.0 CPython 3.10.8

xiaxinmeng avatar Apr 17 '23 02:04 xiaxinmeng

@xiaxinmeng Workaround:

m: int  # define variable
a = [((m := k + 1), k * m) for k in range(5)]
print(a)

The same code without walrus operator:

a = []
for k in range(5):
    m = k + 1
    a.append((m, k * m))
print(a)

elisbyberi avatar Apr 17 '23 12:04 elisbyberi

This is bug on our side. Thank you for the report.

inumanag avatar Jul 26 '23 21:07 inumanag