Similar to Swift, I think it would add to the expressiveness of the language to be able to type-hint a function which might raise any type of Exception
. For example:
def login(username: str, password: str) -> User raises:
resp = requests.post("/login", {
"user": username,
"password": password,
})
resp.raise_for_status()
return User(**resp.json())
Describes a function login
which normally returns a User
object, but may also raise
an Exception
.
Additionally, what if specific types of Exceptions
could be returned?
def login(username: str, password: str) -> User raises ValidationError:
try:
resp = requests.post("/login", {
"user": username,
"password": password,
})
resp.raise_for_status()
except Exception as e:
# Recursively retry the request
return login(username, password)
# Return a User, but raise a ValidationError if the data doesn't conform to the User model
return User(**resp.json())
I am curious what others think of this? Would this make the language better?