Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance http.HTTPStatus with is_* properties that indicate the HTTP status category #95149

Closed
alexei opened this issue Jul 22, 2022 · 3 comments
Labels
type-feature A feature request or enhancement

Comments

@alexei
Copy link
Contributor

alexei commented Jul 22, 2022

Feature or enhancement

Add five properties to http.HTTPStatus that indicate the category the status belongs to:

class HTTPStatus:
    ...

    @property
    def is_informational(self):
        return 100 <= self < 200

    @property
    def is_success(self):
        return 200 <= self < 300

    @property
    def is_redirection(self):
        return 300 <= self < 400

    @property
    def is_client_error(self):
        return 400 <= self < 500

    @property
    def is_server_error(self):
        return 500 <= self < 600

Pitch

Programs that deal with HTTP requests usually need to deal with the various status codes. Oftentimes, knowing the broad category is sufficient to make quick decisions. For example, a client needs to handle responses differently depending on the status code. Assuming status is an HTTPStatus, instead of writing:

if 200 <= status < 300:
    handle_response(response)
elif 300 <= status < 400:
    handle_redirect(response)
elif 400 <= status < 500:
    raise ClientError(status)
elif 500 <= status < 600:
    maybe_retry(response.request)

One could more elegantly write:

if status.is_success:
    handle_response(response)
elif status.is_redirection:
    handle_redirect(response)
elif status.is_client_error:
    raise ClientError(status)
elif status.is_server_error:
    maybe_retry(response.request)

Enums are safer, more readable and more expressive than magic numbers. I think these small additions would only strengthen HTTPStatus.

Let me know if this interests you, and I can open a PR.

@alexei alexei added the type-feature A feature request or enhancement label Jul 22, 2022
@itaispiegel
Copy link

itaispiegel commented Jul 23, 2022

I like this idea :)

@corona10
Copy link
Member

@alexei

Would you like to submit the patch?

@alexei
Copy link
Contributor Author

alexei commented Sep 5, 2022

This is going to be available starting 3.12, see #95453

@alexei alexei closed this as completed Sep 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type-feature A feature request or enhancement
Projects
None yet
Development

No branches or pull requests

3 participants