Skip to content

Return inet and cidr values as ipaddress objects by default #119

Open

Description

@Cito

Since #43 (6.3), objects of the ipaddress module can be passed as parameters everywhere in pg and pgdb, also inline and as elements of arrays and records. Addresses and interfaces are adapted as inet, networks as cidr, as in psycopg 3.

6.3 also added the typecast functions cast_inet() and cast_cidr() in pg.cast and pgdb.cast. Like in psycopg 3, cast_inet() returns an ip_interface() for values with a prefix length and an ip_address() for other values, and cast_cidr() returns an ip_network(). They are not used by default, but can be set with:

from pg.cast import cast_cidr, cast_inet  # or from pgdb.cast

pg.set_typecast('inet', cast_inet)  # or pgdb.set_typecast
pg.set_typecast('cidr', cast_cidr)

By default, inet and cidr values are still returned as strings. Making these casts the default would be a breaking change for code that works with the returned strings: comparisons like row.ip == '10.0.0.1' would silently become false, and json.dumps() or string operations would fail. So I plan to change the default only in 7.0, by adding the two casts to the default typecasts of pg and pgdb.

Notes:

  • macaddr and macaddr8 have no type in the standard library and stay strings (also in psycopg 3).
  • IPv6 addresses with a scope id (fe80::1%eth0) are accepted by Python, but not by PostgreSQL, so they cannot occur in results.

Activity

  1. added this to the 7.0 milestone on Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions