Skip to content

Commit

Permalink
fix: Remove uses of six. googleapis#913
Browse files Browse the repository at this point in the history
  • Loading branch information
sorced-jim committed Mar 1, 2024
1 parent 455f860 commit 05b5b1f
Show file tree
Hide file tree
Showing 6 changed files with 39 additions and 47 deletions.
11 changes: 5 additions & 6 deletions google/cloud/ndb/_gql.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import datetime
import re
import six
import time

from google.cloud.ndb import context as context_module
Expand Down Expand Up @@ -650,7 +649,7 @@ def _args_to_val(self, func, args):
"""
vals = []
for arg in args:
if isinstance(arg, six.string_types + six.integer_types):
if isinstance(arg, (str, int)):
val = query_module.Parameter(arg)
else:
val = arg.Get()
Expand Down Expand Up @@ -774,7 +773,7 @@ def _raise_cast_error(message):
def _time_function(values):
if len(values) == 1:
value = values[0]
if isinstance(value, six.string_types):
if isinstance(value, str):
try:
time_tuple = time.strptime(value, "%H:%M:%S")
except ValueError as error:
Expand All @@ -783,7 +782,7 @@ def _time_function(values):
)
time_tuple = time_tuple[3:]
time_tuple = time_tuple[0:3]
elif isinstance(value, six.integer_types):
elif isinstance(value, int):
time_tuple = (value,)
else:
_raise_cast_error("Invalid argument for time(), {}".format(value))
Expand All @@ -800,7 +799,7 @@ def _time_function(values):
def _date_function(values):
if len(values) == 1:
value = values[0]
if isinstance(value, six.string_types):
if isinstance(value, str):
try:
time_tuple = time.strptime(value, "%Y-%m-%d")[0:6]
except ValueError as error:
Expand All @@ -822,7 +821,7 @@ def _date_function(values):
def _datetime_function(values):
if len(values) == 1:
value = values[0]
if isinstance(value, six.string_types):
if isinstance(value, str):
try:
time_tuple = time.strptime(value, "%Y-%m-%d %H:%M:%S")[0:6]
except ValueError as error:
Expand Down
3 changes: 1 addition & 2 deletions google/cloud/ndb/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import contextvars
import itertools
import os
import six
import threading
import uuid

Expand Down Expand Up @@ -550,7 +549,7 @@ def set_global_cache_timeout_policy(self, policy):
if policy is None:
policy = _default_global_cache_timeout_policy

elif isinstance(policy, six.integer_types):
elif isinstance(policy, int):
timeout = policy

def policy(key):
Expand Down
7 changes: 3 additions & 4 deletions google/cloud/ndb/key.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,6 @@

import base64
import functools
import six

from google.cloud.datastore import _app_engine_key_pb2
from google.cloud.datastore import key as _key_module
Expand Down Expand Up @@ -1245,7 +1244,7 @@ def _from_urlsafe(urlsafe, app, namespace, database):
Tuple[google.cloud.datastore.key.Key, .Reference]: The key
corresponding to ``urlsafe`` and the Reference protobuf.
"""
if isinstance(urlsafe, six.string_types): # pragma: NO BRANCH
if isinstance(urlsafe, str): # pragma: NO BRANCH
urlsafe = urlsafe.encode("ascii")
padding = b"=" * (-len(urlsafe) % 4)
urlsafe += padding
Expand Down Expand Up @@ -1526,7 +1525,7 @@ def _clean_flat_path(flat):
if isinstance(kind, type):
kind = kind._get_kind()
flat[i] = kind
if not isinstance(kind, six.string_types):
if not isinstance(kind, str):
raise TypeError(
"Key kind must be a string or Model class; "
"received {!r}".format(kind)
Expand All @@ -1537,7 +1536,7 @@ def _clean_flat_path(flat):
if id_ is None:
if i + 2 < len(flat):
raise exceptions.BadArgumentError("Incomplete Key entry must be last")
elif not isinstance(id_, six.string_types + six.integer_types):
elif not isinstance(id_, (str, int)):
raise TypeError(_INVALID_ID_TYPE.format(id_))

# Remove trailing ``None`` for a partial key.
Expand Down
56 changes: 27 additions & 29 deletions google/cloud/ndb/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,6 @@ class Person(Model):
import inspect
import json
import pickle
import six
import zlib

import pytz
Expand Down Expand Up @@ -1069,7 +1068,7 @@ def _verify_name(name):
TypeError: If the ``name`` is not a string.
ValueError: If the name contains a ``.``.
"""
if not isinstance(name, six.string_types):
if not isinstance(name, str):
raise TypeError("Name {!r} is not a string".format(name))

if "." in name:
Expand Down Expand Up @@ -2087,7 +2086,7 @@ def _legacy_db_get_value(v, p):
# If this passes, don't return unicode.
except UnicodeDecodeError:
try:
sval = six.text_type(sval.decode("utf-8"))
sval = str(sval.decode("utf-8"))
except UnicodeDecodeError:
pass
return sval
Expand Down Expand Up @@ -2420,7 +2419,7 @@ def _validate(self, value):
.BadValueError: If ``value`` is not an :class:`int` or convertible
to one.
"""
if not isinstance(value, six.integer_types):
if not isinstance(value, int):
raise exceptions.BadValueError(
"In field {}, expected integer, got {!r}".format(self._name, value)
)
Expand Down Expand Up @@ -2452,14 +2451,14 @@ def _validate(self, value):
.BadValueError: If ``value`` is not a :class:`float` or convertible
to one.
"""
if not isinstance(value, six.integer_types + (float,)):
if not isinstance(value, (float, int)):
raise exceptions.BadValueError(
"In field {}, expected float, got {!r}".format(self._name, value)
)
return float(value)


class _CompressedValue(six.binary_type):
class _CompressedValue(bytes):
"""A marker object wrapping compressed values.
Args:
Expand Down Expand Up @@ -2769,7 +2768,7 @@ def _validate(self, value):
.BadValueError: If the current property is indexed but the UTF-8
encoded value exceeds the maximum length (1500 bytes).
"""
if not isinstance(value, six.text_type):
if not isinstance(value, str):
# In Python 2.7, bytes is a synonym for str
if isinstance(value, bytes):
try:
Expand All @@ -2796,7 +2795,7 @@ def _to_base_type(self, value):
:class:`str`, this will return the UTF-8 encoded bytes for it.
Otherwise, it will return :data:`None`.
"""
if isinstance(value, six.text_type):
if isinstance(value, str):
return value.encode("utf-8")

def _from_base_type(self, value):
Expand Down Expand Up @@ -2931,7 +2930,7 @@ def _validate(self, value):
.BadValueError: If the current property is indexed but the UTF-8
encoded value exceeds the maximum length (1500 bytes).
"""
if isinstance(value, six.binary_type):
if isinstance(value, bytes):
try:
encoded_length = len(value)
value = value.decode("utf-8")
Expand All @@ -2941,7 +2940,7 @@ def _validate(self, value):
self._name, value
)
)
elif isinstance(value, six.string_types):
elif isinstance(value, str):
encoded_length = len(value.encode("utf-8"))
else:
raise exceptions.BadValueError("Expected string, got {!r}".format(value))
Expand All @@ -2963,7 +2962,7 @@ def _to_base_type(self, value):
:class:`bytes`, this will return the UTF-8 decoded ``str`` for it.
Otherwise, it will return :data:`None`.
"""
if isinstance(value, six.binary_type):
if isinstance(value, bytes):
return value.decode("utf-8")

def _from_base_type(self, value):
Expand All @@ -2986,7 +2985,7 @@ def _from_base_type(self, value):
:class:`str` corresponding to it. Otherwise, it will return
:data:`None`.
"""
if isinstance(value, six.binary_type):
if isinstance(value, bytes):
try:
return value.decode("utf-8")
except UnicodeError:
Expand Down Expand Up @@ -3194,7 +3193,7 @@ def _from_base_type(self, value):
"""
# We write and retrieve `bytes` normally, but for some reason get back
# `str` from a projection query.
if not isinstance(value, six.text_type):
if not isinstance(value, str):
value = value.decode("ascii")
return json.loads(value)

Expand Down Expand Up @@ -3495,14 +3494,14 @@ def _to_base_type(self, value):
user_entity = ds_entity_module.Entity()

# Set required fields.
user_entity["email"] = six.ensure_text(value.email())
user_entity["email"] = str(value.email())
user_entity.exclude_from_indexes.add("email")
user_entity["auth_domain"] = six.ensure_text(value.auth_domain())
user_entity["auth_domain"] = str(value.auth_domain())
user_entity.exclude_from_indexes.add("auth_domain")
# Set optional field.
user_id = value.user_id()
if user_id:
user_entity["user_id"] = six.ensure_text(user_id)
user_entity["user_id"] = str(user_id)
user_entity.exclude_from_indexes.add("user_id")

return user_entity
Expand Down Expand Up @@ -3597,7 +3596,7 @@ def _handle_positional(wrapped):
@functools.wraps(wrapped)
def wrapper(self, *args, **kwargs):
for arg in args:
if isinstance(arg, six.string_types):
if isinstance(arg, str):
if "name" in kwargs:
raise TypeError("You can only specify name once")

Expand Down Expand Up @@ -3636,7 +3635,7 @@ def __init__(
kind = kind._get_kind()

else:
if kind is not None and not isinstance(kind, six.string_types):
if kind is not None and not isinstance(kind, str):
raise TypeError("Kind must be a Model class or a string")

super(KeyProperty, self).__init__(
Expand Down Expand Up @@ -3918,7 +3917,7 @@ def _from_base_type(self, value):
returns the value without ``tzinfo`` or ``None`` if value did
not have ``tzinfo`` set.
"""
if isinstance(value, six.integer_types):
if isinstance(value, int):
# Projection query, value is integer nanoseconds
seconds = value / 1e6
value = datetime.datetime.fromtimestamp(seconds, pytz.utc)
Expand Down Expand Up @@ -4683,8 +4682,7 @@ def __repr__(cls):
return "{}<{}>".format(cls.__name__, ", ".join(props))


@six.add_metaclass(MetaModel)
class Model(_NotEqualMixin):
class Model(_NotEqualMixin, metaclass=MetaModel):
"""A class describing Cloud Datastore entities.
Model instances are usually called entities. All model classes
Expand Down Expand Up @@ -4950,7 +4948,7 @@ def __init__(_self, **kwargs):

def _get_property_for(self, p, indexed=True, depth=0):
"""Internal helper to get the Property for a protobuf-level property."""
if isinstance(p.name(), six.text_type):
if isinstance(p.name(), str):
p.set_name(bytes(p.name(), encoding="utf-8"))
parts = p.name().decode().split(".")
if len(parts) <= depth:
Expand Down Expand Up @@ -5008,9 +5006,9 @@ def _from_pb(cls, pb, set_key=True, ent=None, key=None):
# A key passed in overrides a key in the pb.
if key is None and pb.key().path.element_size():
# modern NDB expects strings.
if not isinstance(pb.key_.app_, six.text_type): # pragma: NO BRANCH
if not isinstance(pb.key_.app_, str): # pragma: NO BRANCH
pb.key_.app_ = pb.key_.app_.decode()
if not isinstance(pb.key_.name_space_, six.text_type): # pragma: NO BRANCH
if not isinstance(pb.key_.name_space_, str): # pragma: NO BRANCH
pb.key_.name_space_ = pb.key_.name_space_.decode()

key = Key(reference=pb.key())
Expand Down Expand Up @@ -5316,7 +5314,7 @@ def _fix_up_properties(cls):
an underscore.
"""
kind = cls._get_kind()
if not isinstance(kind, six.string_types):
if not isinstance(kind, str):
raise KindError(
"Class {} defines a ``_get_kind()`` method that returns "
"a non-string ({!r})".format(cls.__name__, kind)
Expand Down Expand Up @@ -6046,7 +6044,7 @@ def _get_or_insert_async(_cls, _name, *args, **kwargs):
project = _cls._get_arg(kwargs, "project")
options = kwargs.pop("_options")

if not isinstance(name, six.string_types):
if not isinstance(name, str):
raise TypeError("'name' must be a string; received {!r}".format(name))

elif not name:
Expand Down Expand Up @@ -6651,10 +6649,10 @@ def get_indexes(**options):
def _unpack_user(v):
"""Internal helper to unpack a User value from a protocol buffer."""
uv = v.uservalue()
email = six.text_type(uv.email().decode("utf-8"))
auth_domain = six.text_type(uv.auth_domain().decode("utf-8"))
email = str(uv.email().decode("utf-8"))
auth_domain = str(uv.auth_domain().decode("utf-8"))
obfuscated_gaiaid = uv.obfuscated_gaiaid().decode("utf-8")
obfuscated_gaiaid = six.text_type(obfuscated_gaiaid)
obfuscated_gaiaid = str(obfuscated_gaiaid)

value = User(
email=email,
Expand Down
7 changes: 3 additions & 4 deletions google/cloud/ndb/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,6 @@ def ranked(cls, rank):

import functools
import logging
import six

from google.cloud.ndb import context as context_module
from google.cloud.ndb import exceptions
Expand Down Expand Up @@ -305,7 +304,7 @@ class Parameter(ParameterizedThing):
"""

def __init__(self, key):
if not isinstance(key, six.integer_types + six.string_types):
if not isinstance(key, (int, str)):
raise TypeError(
"Parameter key must be an integer or string, not {}".format(key)
)
Expand Down Expand Up @@ -1677,7 +1676,7 @@ def _to_property_orders(self, order_by):
elif isinstance(order, model.Property):
# use the sign to turn it into a PropertyOrder
orders.append(+order)
elif isinstance(order, six.string_types):
elif isinstance(order, str):
name = order
reverse = False
if order.startswith("-"):
Expand Down Expand Up @@ -2346,7 +2345,7 @@ def _to_property_names(properties):

fixed = []
for prop in properties:
if isinstance(prop, six.string_types):
if isinstance(prop, str):
fixed.append(prop)
elif isinstance(prop, model.Property):
fixed.append(prop._name)
Expand Down
2 changes: 0 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ def main():
"pymemcache >= 2.1.0, < 5.0.0dev",
"pytz >= 2018.3",
"redis >= 3.0.0, < 6.0.0dev",
# TODO(https://github.com/googleapis/python-ndb/issues/913) remove this dependency once six is no longer used in the codebase
"six >= 1.12.0, < 2.0.0dev"
]

setuptools.setup(
Expand Down

0 comments on commit 05b5b1f

Please sign in to comment.