Dropped Python 2.x support in included libs

There is no point in having it and complicates the compatibility
detection.
This commit is contained in:
Salvador E. Tropea 2023-08-08 12:27:06 -03:00
parent 98346bcf39
commit 73097d7963
4 changed files with 59 additions and 160 deletions

View File

@ -42,23 +42,6 @@ __all__ = [
]
__metaclass__ = type
# This allows the code to run on Python 2 and 3 by
# creating a consistent reference for the appropriate
# string class
try:
str_class = unicode
except NameError:
# Python 3 support
str_class = str
# backward compatibility for basestring for python < 2.3
try:
basestring
except NameError:
basestring = str
# Flag for testing
debug = False
@ -169,8 +152,8 @@ path ::= [ "path" [<pathseg>:segment]] => ("simple", segment)
| [ "path" [<pathseg>+:segments] ] => ("complex", u"resolve(context, u'" + u"', u'".join(segments) + u"')" )
complexarg ::= [ "path" [<pathseg>+:segments] ] => u"resolve(context, u'" + u"', u'".join(segments) + u"')"
| [ "subexpr" ["path" <pathseg>:name] [<arg>*:arguments] ] => u'resolve_subexpr(helpers, "' + name + '", context' + (u', ' + u', '.join(arguments) if arguments else u'') + u')'
| [ "literalparam" <anything>:value ] => {str_class}(value)
arg ::= [ "kwparam" <anything>:symbol <complexarg>:a ] => {str_class}(symbol) + '=' + a
| [ "literalparam" <anything>:value ] => {str}(value)
arg ::= [ "kwparam" <anything>:symbol <complexarg>:a ] => {str}(symbol) + '=' + a
| <complexarg>
pathseg ::= "/" => ''
| "." => ''
@ -178,7 +161,7 @@ pathseg ::= "/" => ''
| "this" => ''
pathseg ::= <anything>:symbol => u''.join(symbol)
""" # noqa: E501
compile_grammar = compile_grammar.format(str_class=str_class.__name__)
compile_grammar = compile_grammar.format(str=str.__name__)
class PybarsError(Exception):
@ -190,22 +173,13 @@ class strlist(list):
"""A quasi-list to let the template code avoid special casing."""
def __str__(self): # Python 3
def __str__(self):
return ''.join(self)
def __unicode__(self): # Python 2
return u''.join(self)
def grow(self, thing):
"""Make the list longer, appending for unicode, extending otherwise."""
if type(thing) == str_class:
if type(thing) == str:
self.append(thing)
# This will only ever match in Python 2 since str_class is str in
# Python 3.
elif type(thing) == str:
self.append(unicode(thing)) # noqa: F821 undefined name 'unicode'
else:
# Recursively expand to a flat list; may deserve a C accelerator at
# some point.
@ -238,14 +212,7 @@ def pick(context, name, default=None):
try:
return context[name]
except (KeyError, TypeError, AttributeError):
if isinstance(name, basestring):
try:
exists = hasattr(context, name)
except UnicodeEncodeError:
# Python 2 raises UnicodeEncodeError on non-ASCII strings
pass
else:
if exists:
if isinstance(name, str) and hasattr(context, name):
return getattr(context, name)
if hasattr(context, 'get'):
return context.get(name)
@ -291,14 +258,9 @@ class Scope:
def __len__(self):
return len(self.context)
# Added for Python 3
def __str__(self):
return str(self.context)
# Only called in Python 2
def __unicode__(self):
return unicode(self.context) # noqa: F821 undefined name 'unicode'
def resolve(context, *segments):
carryover_data = False
@ -357,11 +319,11 @@ def prepare(value, should_escape):
return u''
type_ = type(value)
if type_ is not strlist:
if type_ is not str_class:
if type_ is not str:
if type_ is bool:
value = u'true' if value else u'false'
else:
value = str_class(value)
value = str(value)
if should_escape:
value = escape(value)
return value
@ -554,10 +516,10 @@ class CodeBuilder:
# Ensure the result is a string and not a strlist
if len(self.stack) == 0:
self._result.grow(u" if called:\n")
self._result.grow(u" result = %s(result)\n" % str_class.__name__)
self._result.grow(u" result = %s(result)\n" % str.__name__)
self._result.grow(u" return result\n")
source = str_class(u"".join(lines))
source = str(u"".join(lines))
self._result = self.stack and self.stack[-1][0]
self._locals = self.stack and self.stack[-1][1]
@ -819,7 +781,7 @@ class Compiler:
A tuple of (function, source_code)
"""
if not isinstance(source, str_class):
if not isinstance(source, str):
raise PybarsError("Template source must be a unicode string")
source = self.whitespace_control(source)

View File

@ -47,15 +47,8 @@ import struct
import sys
import uuid
from sys import version_info
if version_info < ( 3, 0 ):
from cStringIO import StringIO
else:
from io import StringIO
if version_info < ( 3, 0 ):
BytesIO = StringIO
else:
from io import BytesIO
from io import StringIO
from io import BytesIO
from . import utils
import warnings
@ -64,13 +57,7 @@ from .generic import *
from .utils import readNonWhitespace, readUntilWhitespace, ConvertFunctionsToVirtualList
from .utils import b_, formatWarning, isString, ord_, str_, u_
if version_info < ( 2, 4 ):
from sets import ImmutableSet as frozenset
if version_info < ( 2, 5 ):
from md5 import md5
else:
from hashlib import md5
from hashlib import md5
import uuid

View File

@ -34,18 +34,12 @@ __author_email__ = "biziqe@mathieu.fenniak.net"
import sys
try:
import __builtin__ as builtins
except ImportError: # Py3
import builtins
xrange_fn = range
_basestring = str
xrange_fn = getattr(builtins, "xrange", range)
_basestring = getattr(builtins, "basestring", str)
bytes_type = type(bytes()) # Works the same in Python 2.X and 3.X
string_type = getattr(builtins, "unicode", str)
int_types = (int, long) if sys.version_info[0] < 3 else (int,)
bytes_type = bytes
string_type = str
int_types = (int,)
# Make basic type tests more consistent
@ -222,13 +216,9 @@ class PdfStreamError(PdfReadError):
pass
if sys.version_info[0] < 3:
def b_(s):
return s
else:
B_CACHE = {}
B_CACHE = {}
def b_(s):
def b_(s):
bc = B_CACHE
if s in bc:
return bc[s]
@ -242,16 +232,10 @@ else:
def u_(s):
if sys.version_info[0] < 3:
return unicode(s, 'unicode_escape')
else:
return s
def str_(b):
if sys.version_info[0] < 3:
return b
else:
if type(b) == bytes:
return b.decode('latin-1')
else:
@ -259,30 +243,21 @@ def str_(b):
def ord_(b):
if sys.version_info[0] < 3 or type(b) == str:
if type(b) == str:
return ord(b)
else:
return b
def chr_(c):
if sys.version_info[0] < 3:
return c
else:
return chr(c)
def barray(b):
if sys.version_info[0] < 3:
return b
else:
return bytearray(b)
def hexencode(b):
if sys.version_info[0] < 3:
return b.encode('hex')
else:
import codecs
coder = codecs.getencoder('hex_codec')
return coder(b)[0]

View File

@ -94,32 +94,8 @@ class SExpData(Exception):
pass
# ** Python 3 compatibility
try:
unicode
PY3 = False
except NameError:
basestring = unicode = str # Python 3
PY3 = True
def uformat(s, *args, **kwds):
"""Alias of ``unicode(s).format(...)``."""
return tounicode(s).format(*args, **kwds)
# ** Utility
def tounicode(string):
"""
Decode `string` if it is not unicode. Do nothing in Python 3.
"""
if not isinstance(string, unicode):
string = unicode(string, 'utf-8')
return string
def return_as(converter):
"""
Decorator to convert result of a function.
@ -274,7 +250,7 @@ def dump(obj, filelike, **kwds):
(a b)
"""
filelike.write(unicode(dumps(obj)))
filelike.write(dumps(obj))
def dumps(obj, **kwds):
@ -404,7 +380,7 @@ def tosexp(obj, str_as='string', tuple_as='list',
elif tuple_as == 'array':
res = Bracket(obj, '[').tosexp(_tosexp)
else:
raise ValueError(uformat("tuple_as={0!r} is not valid", tuple_as))
raise ValueError("tuple_as={0!r} is not valid".format(tuple_as))
indent -= c
elif obj is True: # must do this before ``isinstance(obj, int)``
res = true_as
@ -414,13 +390,13 @@ def tosexp(obj, str_as='string', tuple_as='list',
res = none_as
elif isinstance(obj, (int, float)):
res = str(obj)
elif isinstance(obj, basestring):
elif isinstance(obj, str):
if str_as == 'symbol':
res = obj
elif str_as == 'string':
res = String(obj).tosexp()
else:
raise ValueError(uformat("str_as={0!r} is not valid", str_as))
raise ValueError("str_as={0!r} is not valid".format(str_as))
elif isinstance(obj, dict):
res = _tosexp(dict_to_plist(obj))
elif isinstance(obj, SExpBase):
@ -428,16 +404,16 @@ def tosexp(obj, str_as='string', tuple_as='list',
elif isinstance(obj, Sep):
res = '\n' + ' '*indent
else:
raise TypeError(uformat(
raise TypeError(
"Object of type '{0}' cannot be converted by `tosexp`. "
"It's value is '{1!r}'", type(obj), obj))
"It's value is '{1!r}'".format(type(obj), obj))
return res
@return_as(list)
def dict_to_plist(obj):
for key in obj:
yield Symbol(uformat(":{0}", key))
yield Symbol(":{0}".format(key))
yield obj[key]
@ -447,7 +423,7 @@ class SExpBase(object):
self._val = val
def __repr__(self):
return uformat("{0}({1!r})", self.__class__.__name__, self._val)
return "{0}({1!r})".format(self.__class__.__name__, self._val)
def __eq__(self, other):
if isinstance(other, self.__class__):
@ -471,7 +447,7 @@ class SExpBase(object):
def quote(cls, string):
for (s, q) in cls._lisp_quoted_specials:
string = string.replace(s, q)
return tounicode(string)
return string
@classmethod
def unquote(cls, string):
@ -504,13 +480,13 @@ class String(SExpBase):
_lisp_quoted_to_raw = {q: r for (r, q) in _lisp_quoted_specials}
def tosexp(self, tosexp=None):
return uformat('"{0}"', self.quote(self._val))
return '"{0}"'.format(self.quote(self._val))
class Quoted(SExpBase):
def tosexp(self, tosexp=tosexp):
return uformat("'{0}", tosexp(self._val))
return "'{0}".format(tosexp(self._val))
class Bracket(SExpBase):
@ -521,8 +497,7 @@ class Bracket(SExpBase):
self._bra = bra
def __repr__(self):
return uformat("{0}({1!r}, {2!r})",
self.__class__.__name__, self._val, self._bra)
return "{0}({1!r}, {2!r})".format(self.__class__.__name__, self._val, self._bra)
def tosexp(self, tosexp=tosexp):
bra = self._bra
@ -537,7 +512,7 @@ class Bracket(SExpBase):
# Avoid spaces at the end of lines
c = c.rstrip(' ')
c += v
return uformat("{0}{1}{2}", bra, c, ke)
return "{0}{1}{2}".format(bra, c, ke)
def bracket(val, bra):
@ -550,19 +525,19 @@ def bracket(val, bra):
class ExpectClosingBracket(Exception):
def __init__(self, got, expect):
super(ExpectClosingBracket, self).__init__(uformat(
super(ExpectClosingBracket, self).__init__(
"Not enough closing brackets. "
"Expected {0!r} to be the last letter in the sexp. "
"Got: {1!r}", expect, got))
"Got: {1!r}".format(expect, got))
class ExpectNothing(Exception):
def __init__(self, got):
super(ExpectNothing, self).__init__(uformat(
super(ExpectNothing, self).__init__(
"Too many closing brackets. "
"Expected no character left in the sexp. "
"Got: {0!r}", got))
"Got: {0!r}".format(got))
class Parser(object):