Skip to content

Commit 1c9ad5a

Browse files
committed
Refactored to keep the current string-only behavior on Python 3
1 parent e2054de commit 1c9ad5a

File tree

2 files changed

+12
-6
lines changed

2 files changed

+12
-6
lines changed

maxminddb/compat.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,15 @@
11
import sys
22

3+
import ipaddress
4+
35
# pylint: skip-file
46

57
if sys.version_info[0] == 2:
8+
def compat_ip_address(address):
9+
if isinstance(address, bytes):
10+
address = address.decode()
11+
return ipaddress.ip_address(address)
12+
613
int_from_byte = ord
714

815
FileNotFoundError = IOError
@@ -14,6 +21,9 @@ def int_from_bytes(b):
1421

1522
byte_from_int = chr
1623
else:
24+
def compat_ip_address(address):
25+
return ipaddress.ip_address(address)
26+
1727
int_from_byte = lambda x: x
1828

1929
FileNotFoundError = FileNotFoundError

maxminddb/reader.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,8 @@
1414
mmap = None
1515

1616
import struct
17-
import ipaddress
1817

19-
from maxminddb.compat import byte_from_int, int_from_byte
18+
from maxminddb.compat import byte_from_int, int_from_byte, compat_ip_address
2019
from maxminddb.const import MODE_AUTO, MODE_MMAP, MODE_FILE, MODE_MEMORY
2120
from maxminddb.decoder import Decoder
2221
from maxminddb.errors import InvalidDatabaseError
@@ -47,7 +46,6 @@ def __init__(self, database, mode=MODE_AUTO):
4746
* MODE_MEMORY - load database into memory.
4847
* MODE_AUTO - tries MODE_MMAP and then MODE_FILE. Default.
4948
"""
50-
# pylint: disable=redefined-variable-type
5149
if (mode == MODE_AUTO and mmap) or mode == MODE_MMAP:
5250
with open(database, 'rb') as db_file:
5351
self._buffer = mmap.mmap(
@@ -95,10 +93,8 @@ def get(self, ip_address):
9593
Arguments:
9694
ip_address -- an IP address in the standard string notation
9795
"""
98-
if isinstance(ip_address, bytes):
99-
ip_address = ip_address.decode()
10096

101-
address = ipaddress.ip_address(ip_address)
97+
address = compat_ip_address(ip_address)
10298

10399
if address.version == 6 and self._metadata.ip_version == 4:
104100
raise ValueError('Error looking up {0}. You attempted to look up '

0 commit comments

Comments
 (0)