Skip to content

Commit

Permalink
Remove redundant _compat.py
Browse files Browse the repository at this point in the history
  • Loading branch information
hugovk authored and akx committed Sep 14, 2021
1 parent 96acf86 commit 3af52a9
Show file tree
Hide file tree
Showing 31 changed files with 144 additions and 281 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Expand Up @@ -11,7 +11,7 @@
- id: debug-statements
- id: end-of-file-fixer
- id: flake8
exclude: (docs/conf.py|babel/messages/__init__.py|babel/__init__.py|babel/_compat.py|tests/messages/data|scripts/import_cldr.py)
exclude: (docs/conf.py|babel/messages/__init__.py|babel/__init__.py|tests/messages/data|scripts/import_cldr.py)
- id: name-tests-test
args: ['--django']
exclude: (tests/messages/data/)
Expand Down
79 changes: 0 additions & 79 deletions babel/_compat.py

This file was deleted.

4 changes: 2 additions & 2 deletions babel/core.py
Expand Up @@ -9,10 +9,10 @@
:license: BSD, see LICENSE for more details.
"""

import pickle
import os

from babel import localedata
from babel._compat import pickle, string_types
from babel.plural import PluralRule

__all__ = ['UnknownLocaleError', 'Locale', 'default_locale', 'negotiate_locale',
Expand Down Expand Up @@ -262,7 +262,7 @@ def parse(cls, identifier, sep='_', resolve_likely_subtags=True):
return None
elif isinstance(identifier, Locale):
return identifier
elif not isinstance(identifier, string_types):
elif not isinstance(identifier, str):
raise TypeError('Unexpected value for identifier: %r' % (identifier,))

parts = parse_locale(identifier, sep=sep)
Expand Down
13 changes: 5 additions & 8 deletions babel/dates.py
Expand Up @@ -27,7 +27,6 @@

from babel.core import default_locale, get_global, Locale
from babel.util import UTC, LOCALTZ
from babel._compat import string_types, integer_types, number_types, PY2

# "If a given short metazone form is known NOT to be understood in a given
# locale and the parent locale has this value such that it would normally
Expand Down Expand Up @@ -58,10 +57,10 @@ def _get_dt_and_tzinfo(dt_or_tzinfo):
if dt_or_tzinfo is None:
dt = datetime.now()
tzinfo = LOCALTZ
elif isinstance(dt_or_tzinfo, string_types):
elif isinstance(dt_or_tzinfo, str):
dt = None
tzinfo = get_timezone(dt_or_tzinfo)
elif isinstance(dt_or_tzinfo, integer_types):
elif isinstance(dt_or_tzinfo, int):
dt = None
tzinfo = UTC
elif isinstance(dt_or_tzinfo, (datetime, time)):
Expand Down Expand Up @@ -123,7 +122,7 @@ def _get_datetime(instant):
"""
if instant is None:
return datetime_.utcnow()
elif isinstance(instant, integer_types) or isinstance(instant, float):
elif isinstance(instant, int) or isinstance(instant, float):
return datetime_.utcfromtimestamp(instant)
elif isinstance(instant, time):
return datetime_.combine(date.today(), instant)
Expand Down Expand Up @@ -173,7 +172,7 @@ def _get_time(time, tzinfo=None):
"""
if time is None:
time = datetime.utcnow()
elif isinstance(time, number_types):
elif isinstance(time, (int, float)):
time = datetime.utcfromtimestamp(time)
if time.tzinfo is None:
time = time.replace(tzinfo=UTC)
Expand Down Expand Up @@ -201,7 +200,7 @@ def get_timezone(zone=None):
"""
if zone is None:
return LOCALTZ
if not isinstance(zone, string_types):
if not isinstance(zone, str):
return zone
try:
return _pytz.timezone(zone)
Expand Down Expand Up @@ -1227,8 +1226,6 @@ def __unicode__(self):

def __str__(self):
pat = self.pattern
if PY2:
pat = pat.encode('utf-8')
return pat

def __mod__(self, other):
Expand Down
8 changes: 4 additions & 4 deletions babel/localedata.py
Expand Up @@ -12,14 +12,14 @@
:license: BSD, see LICENSE for more details.
"""

import pickle
import os
import re
import sys
import threading
from collections import abc
from itertools import chain

from babel._compat import pickle, string_types, abc


_cache = {}
_cache_lock = threading.RLock()
Expand All @@ -33,7 +33,7 @@ def normalize_locale(name):
Returns the normalized locale ID string or `None` if the ID is not
recognized.
"""
if not name or not isinstance(name, string_types):
if not name or not isinstance(name, str):
return None
name = name.strip().lower()
for locale_id in chain.from_iterable([_cache, locale_identifiers()]):
Expand Down Expand Up @@ -64,7 +64,7 @@ def exists(name):
:param name: the locale identifier string
"""
if not name or not isinstance(name, string_types):
if not name or not isinstance(name, str):
return False
if name in _cache:
return True
Expand Down
47 changes: 19 additions & 28 deletions babel/messages/catalog.py
Expand Up @@ -23,8 +23,7 @@
from babel.core import Locale, UnknownLocaleError
from babel.dates import format_datetime
from babel.messages.plurals import get_plural
from babel.util import distinct, LOCALTZ, FixedOffsetTimezone
from babel._compat import string_types, number_types, PY2, cmp, text_type, force_text
from babel.util import distinct, LOCALTZ, FixedOffsetTimezone, _cmp

__all__ = ['Message', 'Catalog', 'TranslationError']

Expand Down Expand Up @@ -106,7 +105,7 @@ def __init__(self, id, string=u'', locations=(), flags=(), auto_comments=(),
self.flags.discard('python-format')
self.auto_comments = list(distinct(auto_comments))
self.user_comments = list(distinct(user_comments))
if isinstance(previous_id, string_types):
if isinstance(previous_id, str):
self.previous_id = [previous_id]
else:
self.previous_id = list(previous_id)
Expand All @@ -123,7 +122,7 @@ def values_to_compare(obj):
if isinstance(obj, Message) and obj.pluralizable:
return obj.id[0], obj.context or ''
return obj.id, obj.context or ''
return cmp(values_to_compare(self), values_to_compare(other))
return _cmp(values_to_compare(self), values_to_compare(other))

def __gt__(self, other):
return self.__cmp__(other) > 0
Expand Down Expand Up @@ -224,21 +223,6 @@ class TranslationError(Exception):
#"""


if PY2:
def _parse_header(header_string):
# message_from_string only works for str, not for unicode
headers = message_from_string(header_string.encode('utf8'))
decoded_headers = {}
for name, value in headers.items():
name = name.decode('utf8')
value = value.decode('utf8')
decoded_headers[name] = value
return decoded_headers

else:
_parse_header = message_from_string


class Catalog(object):
"""Representation of a message catalog."""

Expand Down Expand Up @@ -307,12 +291,12 @@ def _set_locale(self, locale):
return

if isinstance(locale, Locale):
self._locale_identifier = text_type(locale)
self._locale_identifier = str(locale)
self._locale = locale
return

if isinstance(locale, string_types):
self._locale_identifier = text_type(locale)
if isinstance(locale, str):
self._locale_identifier = str(locale)
try:
self._locale = Locale.parse(locale)
except UnknownLocaleError:
Expand Down Expand Up @@ -388,7 +372,7 @@ def _get_mime_headers(self):
headers.append(('POT-Creation-Date',
format_datetime(self.creation_date, 'yyyy-MM-dd HH:mmZ',
locale='en')))
if isinstance(self.revision_date, (datetime, time_) + number_types):
if isinstance(self.revision_date, (datetime, time_, int, float)):
headers.append(('PO-Revision-Date',
format_datetime(self.revision_date,
'yyyy-MM-dd HH:mmZ', locale='en')))
Expand All @@ -412,10 +396,17 @@ def _get_mime_headers(self):
headers.append(('Generated-By', 'Babel %s\n' % VERSION))
return headers

def _force_text(self, s, encoding='utf-8', errors='strict'):
if isinstance(s, str):
return s
if isinstance(s, bytes):
return s.decode(encoding, errors)
return str(s)

def _set_mime_headers(self, headers):
for name, value in headers:
name = force_text(name.lower(), encoding=self.charset)
value = force_text(value, encoding=self.charset)
name = self._force_text(name.lower(), encoding=self.charset)
value = self._force_text(value, encoding=self.charset)
if name == 'project-id-version':
parts = value.split(' ')
self.project = u' '.join(parts[:-1])
Expand Down Expand Up @@ -523,7 +514,7 @@ def plural_expr(self):
>>> Catalog(locale='ding').plural_expr # unknown locale
'(n != 1)'
:type: `string_types`"""
:type: `str`"""
if self._plural_expr is None:
expr = '(n != 1)'
if self.locale:
Expand Down Expand Up @@ -625,7 +616,7 @@ def __setitem__(self, id, message):
message = current
elif id == '':
# special treatment for the header message
self.mime_headers = _parse_header(message.string).items()
self.mime_headers = message_from_string(message.string).items()
self.header_comment = '\n'.join([('# %s' % c).rstrip() for c
in message.user_comments])
self.fuzzy = message.fuzzy
Expand Down Expand Up @@ -773,7 +764,7 @@ def _merge(message, oldkey, newkey):
fuzzy = True
fuzzy_matches.add(oldkey)
oldmsg = messages.get(oldkey)
if isinstance(oldmsg.id, string_types):
if isinstance(oldmsg.id, str):
message.previous_id = [oldmsg.id]
else:
message.previous_id = list(oldmsg.id)
Expand Down
7 changes: 3 additions & 4 deletions babel/messages/checkers.py
Expand Up @@ -12,7 +12,6 @@
"""

from babel.messages.catalog import TranslationError, PYTHON_FORMAT
from babel._compat import string_types, izip


#: list of format chars that are compatible to each other
Expand All @@ -26,7 +25,7 @@
def num_plurals(catalog, message):
"""Verify the number of plurals in the translation."""
if not message.pluralizable:
if not isinstance(message.string, string_types):
if not isinstance(message.string, str):
raise TranslationError("Found plural forms for non-pluralizable "
"message")
return
Expand Down Expand Up @@ -54,7 +53,7 @@ def python_format(catalog, message):
if not isinstance(msgstrs, (list, tuple)):
msgstrs = (msgstrs,)

for msgid, msgstr in izip(msgids, msgstrs):
for msgid, msgstr in zip(msgids, msgstrs):
if msgstr:
_validate_format(msgid, msgstr)

Expand Down Expand Up @@ -134,7 +133,7 @@ def _check_positional(results):
if len(a) != len(b):
raise TranslationError('positional format placeholders are '
'unbalanced')
for idx, ((_, first), (_, second)) in enumerate(izip(a, b)):
for idx, ((_, first), (_, second)) in enumerate(zip(a, b)):
if not _compatible(first, second):
raise TranslationError('incompatible format for placeholder '
'%d: %r and %r are not compatible' %
Expand Down

0 comments on commit 3af52a9

Please sign in to comment.