Skip to content

Commit 0d2cbf8

Browse files
Gábor BorosGábor Boros
Gábor Boros
authored and
Gábor Boros
committed
Make files Py3 only compatible
1 parent f9ea46e commit 0d2cbf8

File tree

14 files changed

+41
-119
lines changed

14 files changed

+41
-119
lines changed

rethinkdb/__init__.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,15 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
# The builtins here defends against re-importing something obscuring `object`.
15+
import builtins
1416
import imp
1517
import os
1618

1719
import pkg_resources
1820

1921
from rethinkdb import errors, version
2022

21-
# The builtins here defends against re-importing something obscuring `object`.
22-
try:
23-
import __builtin__ as builtins # Python 2
24-
except ImportError:
25-
import builtins # Python 3
26-
27-
2823
__all__ = ["RethinkDB"] + errors.__all__
2924
__version__ = version.VERSION
3025

rethinkdb/_dump.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020

2121
"""`rethinkdb-dump` creates an archive of data from a RethinkDB cluster"""
2222

23-
from __future__ import print_function
2423

2524
import datetime
2625
import os

rethinkdb/_export.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
# This file incorporates work covered by the following copyright:
1818
# Copyright 2010-2016 RethinkDB, all rights reserved.
1919

20-
from __future__ import print_function
2120

2221
import csv
2322
import ctypes
@@ -41,9 +40,9 @@
4140
from rethinkdb.logger import default_logger
4241

4342
try:
44-
unicode
43+
str
4544
except NameError:
46-
unicode = str
45+
str = str
4746

4847

4948
usage = """rethinkdb export [-c HOST:PORT] [-p] [--password-file FILENAME] [--tls-cert filename] [-d DIR]
@@ -244,13 +243,8 @@ def csv_writer(filename, fields, delimiter, task_queue, error_queue):
244243
info.append(str(row[field]))
245244
elif isinstance(row[field], str):
246245
info.append(row[field])
247-
elif isinstance(row[field], unicode):
248-
info.append(row[field].encode("utf-8"))
249246
else:
250-
if str == unicode:
251-
info.append(json.dumps(row[field]))
252-
else:
253-
info.append(json.dumps(row[field]).encode("utf-8"))
247+
info.append(json.dumps(row[field]))
254248
out_writer.writerow(info)
255249
item = task_queue.get()
256250
except BaseException:

rethinkdb/_import.py

Lines changed: 6 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919

2020
"""`rethinkdb import` loads data into a RethinkDB cluster"""
2121

22-
from __future__ import print_function
2322

2423
import codecs
2524
import collections
@@ -34,23 +33,13 @@
3433
import time
3534
import traceback
3635
from multiprocessing.queues import Queue, SimpleQueue
36+
from queue import Empty, Full
3737

3838
import six
3939

4040
from rethinkdb import ast, errors, query, utils_common
4141
from rethinkdb.logger import default_logger
4242

43-
try:
44-
unicode
45-
except NameError:
46-
unicode = str
47-
48-
try:
49-
from Queue import Empty, Full
50-
except ImportError:
51-
from queue import Empty, Full
52-
53-
5443
# json parameters
5544
JSON_READ_CHUNK_SIZE = 128 * 1024
5645
JSON_MAX_BUFFER_SIZE = 128 * 1024 * 1024
@@ -125,8 +114,8 @@ def __init__(
125114

126115
# source
127116
if hasattr(source, "read"):
128-
if unicode != str or "b" in source.mode:
129-
# Python2.x or binary file, assume utf-8 encoding
117+
if "b" in source.mode:
118+
# binary file, assume utf-8 encoding
130119
self._source = codecs.getreader("utf-8")(source)
131120
else:
132121
# assume that it has the right encoding on it
@@ -277,7 +266,7 @@ def setup_table(self):
277266
query.row,
278267
**self.source_options["create_args"]
279268
if "create_args" in self.source_options
280-
else {}
269+
else {},
281270
)
282271
),
283272
)
@@ -657,12 +646,7 @@ def byte_counter(self):
657646

658647
for line in self._source:
659648
self._bytes_read.value += len(line)
660-
if unicode != str:
661-
yield line.encode(
662-
"utf-8"
663-
) # Python2.x csv module does not really handle unicode
664-
else:
665-
yield line
649+
yield line
666650

667651
def setup_file(self, warning_queue=None):
668652
# - setup csv.reader with a byte counter wrapper
@@ -699,7 +683,7 @@ def get_line(self):
699683
# treat empty fields as no entry rather than empty string
700684
if value == "":
701685
continue
702-
row[key] = value if str == unicode else unicode(value, encoding="utf-8")
686+
row[key] = value
703687

704688
return row
705689

rethinkdb/_index_rebuild.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
This should be used after upgrading to a newer version of rethinkdb. There
2323
will be a notification in the web UI if any secondary indexes are out-of-date."""
2424

25-
from __future__ import print_function
2625

2726
import sys
2827
import time

rethinkdb/_restore.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020

2121
"""`rethinkdb restore` loads data into a RethinkDB cluster from an archive"""
2222

23-
from __future__ import print_function
2423

2524
import copy
2625
import multiprocessing

rethinkdb/ast.py

Lines changed: 11 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -30,16 +30,6 @@
3030

3131
P_TERM = ql2_pb2.Term.TermType
3232

33-
try:
34-
unicode
35-
except NameError:
36-
unicode = str
37-
38-
try:
39-
xrange
40-
except NameError:
41-
xrange = range
42-
4333

4434
def dict_items(dictionary):
4535
return list(dictionary.items())
@@ -101,7 +91,7 @@ def expr(val, nesting_depth=20):
10191
return ISO8601(val.isoformat())
10292
elif isinstance(val, RqlBinary):
10393
return Binary(val)
104-
elif isinstance(val, (str, unicode)):
94+
elif isinstance(val, str):
10595
return Datum(val)
10696
elif isinstance(val, bytes):
10797
return Binary(val)
@@ -635,7 +625,7 @@ def set_infix(self):
635625
def compose(self, args, optargs):
636626
t_args = [
637627
T("r.expr(", args[i], ")") if needs_wrap(self._args[i]) else args[i]
638-
for i in xrange(len(args))
628+
for i in range(len(args))
639629
]
640630

641631
if self.infix:
@@ -648,7 +638,7 @@ class RqlBiOperQuery(RqlQuery):
648638
def compose(self, args, optargs):
649639
t_args = [
650640
T("r.expr(", args[i], ")") if needs_wrap(self._args[i]) else args[i]
651-
for i in xrange(len(args))
641+
for i in range(len(args))
652642
]
653643
return T("(", T(*t_args, intsp=[" ", self.statement, " "]), ")")
654644

@@ -901,7 +891,7 @@ class MakeObj(RqlQuery):
901891
def __init__(self, obj_dict):
902892
super(MakeObj, self).__init__()
903893
for key, value in dict_items(obj_dict):
904-
if not isinstance(key, (str, unicode)):
894+
if not isinstance(key, str):
905895
raise ReqlDriverCompileError("Object keys must be strings.")
906896
self.optargs[key] = expr(value)
907897

@@ -913,7 +903,7 @@ def compose(self, args, optargs):
913903
"r.expr({",
914904
T(
915905
*[T(repr(key), ": ", value) for key, value in dict_items(optargs)],
916-
intsp=", "
906+
intsp=", ",
917907
),
918908
"})",
919909
)
@@ -1712,7 +1702,7 @@ def __new__(cls, *args, **kwargs):
17121702

17131703
def __repr__(self):
17141704
excerpt = binascii.hexlify(self[0:6]).decode("utf-8")
1715-
excerpt = " ".join([excerpt[i : i + 2] for i in xrange(0, len(excerpt), 2)])
1705+
excerpt = " ".join([excerpt[i : i + 2] for i in range(0, len(excerpt), 2)])
17161706
excerpt = (
17171707
", '%s%s'" % (excerpt, "..." if len(self) > 6 else "")
17181708
if len(self) > 0
@@ -1737,7 +1727,7 @@ def __init__(self, data):
17371727
# Python 3 - `unicode` is equivalent to `str`, neither will be accepted
17381728
if isinstance(data, RqlQuery):
17391729
RqlTopLevelQuery.__init__(self, data)
1740-
elif isinstance(data, unicode):
1730+
elif isinstance(data, str):
17411731
raise ReqlDriverCompileError(
17421732
"Cannot convert a unicode string to binary, "
17431733
"use `unicode.encode()` to specify the "
@@ -1956,11 +1946,9 @@ def __init__(self, lmbd):
19561946
super(Func, self).__init__()
19571947
vrs = []
19581948
vrids = []
1959-
try:
1960-
code = lmbd.func_code
1961-
except AttributeError:
1962-
code = lmbd.__code__
1963-
for i in xrange(code.co_argcount):
1949+
code = lmbd.__code__
1950+
1951+
for i in range(code.co_argcount):
19641952
Func.lock.acquire()
19651953
var_id = Func.nextVarId
19661954
Func.nextVarId += 1
@@ -1976,7 +1964,7 @@ def compose(self, args, optargs):
19761964
"lambda ",
19771965
T(
19781966
*[v.compose([v._args[0].compose(None, None)], []) for v in self.vrs],
1979-
intsp=", "
1967+
intsp=", ",
19801968
),
19811969
": ",
19821970
args[1],

rethinkdb/docs.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@
190190
b"cursor.close()\n\nClose a cursor. Closing a cursor cancels the corresponding query and frees the memory\nassociated with the open request.\n\n*Example* Close a cursor.\n\n cursor.close()\n",
191191
),
192192
(
193-
rethinkdb.net.Cursor.next,
193+
rethinkdb.net.Cursor.__next__,
194194
b"cursor.next([wait=True])\n\nGet the next element in the cursor.\n\nThe optional `wait` argument specifies whether to wait for the next available element and how long to wait:\n\n* `True`: Wait indefinitely (the default).\n* `False`: Do not wait at all. If data is immediately available, it will be returned; if it is not available, a `ReqlTimeoutError` will be raised.\n* number: Wait up to the specified number of seconds for data to be available before raising `ReqlTimeoutError`.\n\nThe behavior of `next` will be identical with `False`, `None` or the number `0`.\n\nCalling `next` the first time on a cursor provides the first element of the cursor. If the data set is exhausted (e.g., you have retrieved all the documents in a table), a `ReqlCursorEmpty` error will be raised when `next` is called.\n\n*Example* Retrieve the next element.\n\n cursor = r.table('superheroes').run(conn)\n doc = cursor.next()\n\n*Example* Retrieve the next element on a [changefeed](http://rethinkdb.com/docs/changefeeds/python), waiting up to five seconds.\n\n cursor = r.table('superheroes').changes().run(conn)\n doc = cursor.next(wait=5)\n\n__Note:__ RethinkDB sequences can be iterated through via the Python Iterable interface. The canonical way to retrieve all the results is to use a [for...in](../each/) loop or [list()](../to_array/).\n\n",
195195
),
196196
(

rethinkdb/errors.py

Lines changed: 4 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -44,38 +44,13 @@
4444
"RqlTimeoutError",
4545
]
4646

47-
import sys
48-
49-
try:
50-
unicode
51-
52-
def convertForPrint(inputString):
53-
if isinstance(inputString, unicode): # noqa: F821
54-
encoding = "utf-8"
55-
if hasattr(sys.stdout, "encoding") and sys.stdout.encoding:
56-
encoding = sys.stdout.encoding
57-
return inputString.encode(encoding or "utf-8", "replace")
58-
else:
59-
return str(inputString)
60-
61-
62-
except NameError:
63-
64-
def convertForPrint(inputString):
65-
return inputString
66-
67-
68-
try:
69-
{}.iteritems
70-
71-
def dict_items(d):
72-
return d.iteritems()
7347

48+
def convertForPrint(inputString):
49+
return inputString
7450

75-
except AttributeError:
7651

77-
def dict_items(d):
78-
return d.items()
52+
def dict_items(d):
53+
return list(d.items())
7954

8055

8156
class ReqlCursorEmpty(Exception):

rethinkdb/handshake.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,6 @@
3131
from rethinkdb.helpers import chain_to_bytes, decode_utf8
3232
from rethinkdb.logger import default_logger
3333

34-
try:
35-
xrange
36-
except NameError:
37-
xrange = range
38-
3934

4035
def compare_digest(digest_a, digest_b):
4136
if sys.version_info[0] == 3:
@@ -96,7 +91,7 @@ def digest(msg, mac=mac):
9691

9792
t = digest(salt + b"\x00\x00\x00\x01")
9893
u = from_bytes(t)
99-
for c in xrange(iterations - 1):
94+
for c in range(iterations - 1):
10095
t = digest(t)
10196
u ^= from_bytes(t)
10297

@@ -339,7 +334,7 @@ def _prepare_auth_request(self, response):
339334
struct.unpack("32B", client_key),
340335
struct.unpack("32B", client_signature),
341336
)
342-
)
337+
),
343338
)
344339

345340
authentication_request = chain_to_bytes(

0 commit comments

Comments
 (0)