exaloop / codon

A high-performance, zero-overhead, extensible Python compiler using LLVM
https://docs.exaloop.io/codon
Other
13.96k stars 498 forks source link

Custom exceptions failed to compile #405

Open likecodingloveproblems opened 1 year ago

likecodingloveproblems commented 1 year ago

This code works as expected in python but failed to compile.

class CustomException(Exception):
    pass

def raise_exception():
    raise CustomException("custom exception raised")

raise_exception()

this is the command to compile. codon build -release -exe custom_exception.py And the output:

custom_exception.py:6:5-53: error: exceptions must derive from BaseException
╰─ custom_exception.py:9:1-16: error: during the realization of raise_exception()
elisbyberi commented 1 year ago

isinstance() returns False for an instance of a derived class.

class A:
    pass

class B(A):
    pass

print(isinstance(B(), A))  # False
print(isinstance(B(), B))  # True

An instance of a derived class is an instance of the base class too, it should return True.

likecodingloveproblems commented 1 year ago

I expect compiled version work the same way as the CPython. @elisbyberi But It doesn't!

elisbyberi commented 1 year ago

@likecodingloveproblems I was discussing the issue in detail. It's not specifically related to the exceptions themselves. It actually pertains to the isinstance() function not returning true for an instance of a derived class: https://github.com/exaloop/codon/blob/e95f778df10c7998714afef6ef99c853eb1694bb/stdlib/internal/internal.codon#L429

arshajii commented 1 year ago

Hi @likecodingloveproblems -- right now defining custom exceptions is a bit different than in Python. We want to update it so your code works as expected. Here is a version that works now:

class CustomException(Static[Exception]):  # don't use polymorphism on exception types
    def __init__(self, msg: str = ""):
        super().__init__("CustomException", msg)  # base exception takes type name as string

def foo():
    raise CustomException("custom exception raised")

try:
    foo()
except CustomException as e:
    print(str(e))
inumanag commented 11 months ago

Yes: the Python-compatible way of handling exceptions will be there in the next versions.