-
Notifications
You must be signed in to change notification settings - Fork 278
Description
The only form of cast expression we have is intended to completely bypass the type system. This is like most forms of casting in C (not counting conversions) -- it never fails either at runtime or at compile time.
Maybe we can add two new types of casts:
Downcast
downcast(T, E) checks at compile time that the type of expression E is a supertype of T, and checks at runtime that E is in fact an instance of T. As a special case, if the type of E is Any, the compile time check always succeeds, but the runtime check is still performed.
A possible implementation:
def downcast(type, expr):
assert isinstance(expr, type)
return exprIt's intentional that this uses assert (though debatable): the intended use case is currently handled by inserting the same assert manually. IOW:
x = downcast(type, expr)is roughly equivalent to:
assert isinstance(expr, type)
x = exprUpcast
Probably much less needed, but proposed for symmetry and because occasionally it's useful. upcast(T, E) should check at compile time that T is a supertype of the type of E, and at runtime it's a no-op.
A possible implementation:
def upcast(type, expr):
return exprThis fragment:
x = upcast(type, expr)is roughly equivalent to:
x: type = exprexcept that it works even if the type of x has already been declared.