Skip to content

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

Closed
@alexei

Description

@alexei

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions