lpython icon indicating copy to clipboard operation
lpython copied to clipboard

Import causes unhandled exception

Open swamishiju opened this issue 9 months ago • 3 comments

import string
print(string.ascii_uppercase)

The above code runs without any issue but

import string

simply importing causes an unhandled exception

$ lpython issue/main.py
ASR verify pass error: Module __main__ dependencies must contain string because a function present in it is getting called in __main__.
Internal Compiler Error: Unhandled exception

swamishiju avatar Mar 13 '25 12:03 swamishiju

Well i found another issue with imports I believe both are linked

from lpython import i32


class Foo:
    def __init__(self: "Foo", a: i32):
        self.a: i32 = a

    def bar(self: "Foo") -> i32:
        return self.a


def bux() -> i32:
    f: Foo = Foo(10)
    return f.bar()


print(bux())

The above code works and gives output

$ lpython main.py
10

When we move the class definition into a separate python file

foo.py

from lpython import i32


class Foo:
    def __init__(self: "Foo", a: i32):
        self.a: i32 = a

    def bar(self: "Foo") -> i32:
        return self.a


def bux() -> i32:
    f: Foo = Foo(10)
    return f.bar()

main.py

import foo

print(foo.bux())

Now this code gives Internal Compiler Error: Unhandled exception but both give the same output with CPython

swamishiju avatar Mar 15 '25 12:03 swamishiju

I think I've found the issue. Import dependency checking doesn't ignore the local use of module variables. Below is a minimal reproduction of the error.

foo.py

a:i32 = 10
b:i32 = a + 10

main.py

import foo

Here the asr verifier sees that b needs as a dependencya which in turn leads foo to have itself as a dependency. This is what I think is happening, there are still a couple details to work out like how does it work when the import is used but I'll start working on a fix and open a PR.

swamishiju avatar Mar 15 '25 14:03 swamishiju

Related issue to the first one

foo.py

print("Hello,World")

bar.py

import foo

main.py

import foo
import bar
$ python main.py
Hello,World

$ lpython -I. main.py
Hello,World
Hello,World

swamishiju avatar Mar 23 '25 11:03 swamishiju