Skip to content

Add safer types of casts #565

Description

@gvanrossum

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:

defdowncast(type, expr):
assertisinstance(expr, type)
returnexpr

It'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:

assertisinstance(expr, type)
x=expr

Upcast

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:

defupcast(type, expr):
returnexpr

This fragment:

x=upcast(type, expr)

is roughly equivalent to:

x: type=expr

except that it works even if the type of x has already been declared.

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: featureDiscussions about new features for Python's type annotations

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions