Remove hy._compat's type aliases

This commit is contained in:
Kodi Arfer 2019-05-20 15:18:12 -04:00
parent b130e3284e
commit bba97ab2a6
10 changed files with 46 additions and 63 deletions

View File

@ -17,11 +17,6 @@ PY38 = sys.version_info >= (3, 8)
# It is always true on Pythons >= 3.3, which use USC-4 on all systems. # It is always true on Pythons >= 3.3, which use USC-4 on all systems.
UCS4 = sys.maxunicode == 0x10FFFF UCS4 = sys.maxunicode == 0x10FFFF
str_type = str if PY3 else unicode # NOQA
bytes_type = bytes if PY3 else str # NOQA
long_type = int if PY3 else long # NOQA
string_types = str if PY3 else basestring # NOQA
# #
# Inspired by the same-named `six` functions. # Inspired by the same-named `six` functions.
# #

View File

@ -14,8 +14,7 @@ from hy.errors import (HyCompileError, HyTypeError, HyLanguageError,
from hy.lex import mangle, unmangle, hy_parse, parse_one_thing, LexException from hy.lex import mangle, unmangle, hy_parse, parse_one_thing, LexException
from hy._compat import (string_types, str_type, bytes_type, long_type, PY3, from hy._compat import (PY3, PY36, PY38, reraise)
PY36, PY38, reraise)
from hy.macros import require, load_macros, macroexpand, tag_macroexpand from hy.macros import require, load_macros, macroexpand, tag_macroexpand
import hy.core import hy.core
@ -512,7 +511,7 @@ class HyASTCompiler(object):
compiled_value = self.compile(value) compiled_value = self.compile(value)
ret += compiled_value ret += compiled_value
arg = str_type(expr)[1:] arg = str(expr)[1:]
keywords.append(asty.keyword( keywords.append(asty.keyword(
expr, arg=ast_str(arg), value=compiled_value.force_expr)) expr, arg=ast_str(arg), value=compiled_value.force_expr))
@ -1358,7 +1357,7 @@ class HyASTCompiler(object):
def compile_maths_expression(self, expr, root, args): def compile_maths_expression(self, expr, root, args):
if len(args) == 0: if len(args) == 0:
# Return the identity element for this operator. # Return the identity element for this operator.
return asty.Num(expr, n=long_type( return asty.Num(expr, n=(
{"+": 0, "|": 0, "*": 1}[root])) {"+": 0, "|": 0, "*": 1}[root]))
if len(args) == 1: if len(args) == 1:
@ -1763,7 +1762,7 @@ class HyASTCompiler(object):
@builds_model(HyInteger, HyFloat, HyComplex) @builds_model(HyInteger, HyFloat, HyComplex)
def compile_numeric_literal(self, x): def compile_numeric_literal(self, x):
f = {HyInteger: long_type, f = {HyInteger: int,
HyFloat: float, HyFloat: float,
HyComplex: complex}[type(x)] HyComplex: complex}[type(x)]
return asty.Num(x, n=f(x)) return asty.Num(x, n=f(x))
@ -1810,9 +1809,9 @@ class HyASTCompiler(object):
def compile_string(self, string): def compile_string(self, string):
if type(string) is HyString and string.is_format: if type(string) is HyString and string.is_format:
# This is a format string (a.k.a. an f-string). # This is a format string (a.k.a. an f-string).
return self._format_string(string, str_type(string)) return self._format_string(string, str(string))
node = asty.Bytes if PY3 and type(string) is HyBytes else asty.Str node = asty.Bytes if PY3 and type(string) is HyBytes else asty.Str
f = bytes_type if type(string) is HyBytes else str_type f = bytes if type(string) is HyBytes else str
return node(string, s=f(string)) return node(string, s=f(string))
def _format_string(self, string, rest, allow_recursion=True): def _format_string(self, string, rest, allow_recursion=True):
@ -1859,7 +1858,7 @@ class HyASTCompiler(object):
try: try:
model, item = parse_one_thing(item) model, item = parse_one_thing(item)
except (ValueError, LexException) as e: except (ValueError, LexException) as e:
raise self._syntax_error(string, "f-string: " + str_type(e)) raise self._syntax_error(string, "f-string: " + str(e))
# Look for a conversion character. # Look for a conversion character.
item = item.lstrip() item = item.lstrip()
@ -1933,7 +1932,7 @@ def get_compiler_module(module=None, compiler=None, calling_frame=False):
module = getattr(compiler, 'module', None) or module module = getattr(compiler, 'module', None) or module
if isinstance(module, string_types): if isinstance(module, str):
if module.startswith('<') and module.endswith('>'): if module.startswith('<') and module.endswith('>'):
module = types.ModuleType(module) module = types.ModuleType(module)
else: else:
@ -2098,7 +2097,7 @@ def hy_compile(tree, module, root=ast.Module, get_expr=False,
""" """
module = get_compiler_module(module, compiler, False) module = get_compiler_module(module, compiler, False)
if isinstance(module, string_types): if isinstance(module, str):
if module.startswith('<') and module.endswith('>'): if module.startswith('<') and module.endswith('>'):
module = types.ModuleType(module) module = types.ModuleType(module)
else: else:

View File

@ -9,7 +9,7 @@ import sys
import hy.macros import hy.macros
import hy.compiler import hy.compiler
from hy._compat import builtins, string_types from hy._compat import builtins
docomplete = True docomplete = True
@ -78,7 +78,7 @@ class Completer(object):
matches = [] matches = []
for p in self.path: for p in self.path:
for k in p.keys(): for k in p.keys():
if isinstance(k, string_types): if isinstance(k, str):
k = k.replace("_", "-") k = k.replace("_", "-")
if k.startswith(text): if k.startswith(text):
matches.append(k) matches.append(k)
@ -89,7 +89,7 @@ class Completer(object):
matches = [] matches = []
for p in self.tag_path: for p in self.tag_path:
for k in p.keys(): for k in p.keys():
if isinstance(k, string_types): if isinstance(k, str):
if k.startswith(text): if k.startswith(text):
matches.append("#{}".format(k)) matches.append("#{}".format(k))
return matches return matches

View File

@ -7,7 +7,7 @@
re re
datetime datetime
collections collections
[hy._compat [PY3 PY36 str-type bytes-type long-type]] [hy._compat [PY36]]
[hy.models [HyObject HyExpression HySymbol HyKeyword HyInteger HyFloat HyComplex HyList HyDict HySet HyString HyBytes]]) [hy.models [HyObject HyExpression HySymbol HyKeyword HyInteger HyFloat HyComplex HyList HyDict HySet HyString HyBytes]])
(try (try
@ -84,10 +84,10 @@
(+ "(" (-cat x) ")")))) (+ "(" (-cat x) ")"))))
(hy-repr-register [HySymbol HyKeyword] str) (hy-repr-register [HySymbol HyKeyword] str)
(hy-repr-register [str-type bytes-type] (fn [x] (hy-repr-register [str bytes] (fn [x]
(setv r (.lstrip (-base-repr x) "ub")) (setv r (.lstrip (-base-repr x) "ub"))
(+ (+
(if (instance? bytes-type x) "b" "") (if (instance? bytes x) "b" "")
(if (.startswith "\"" r) (if (.startswith "\"" r)
; If Python's built-in repr produced a double-quoted string, use ; If Python's built-in repr produced a double-quoted string, use
; that. ; that.
@ -96,10 +96,6 @@
; convert it. ; convert it.
(+ "\"" (.replace (cut r 1 -1) "\"" "\\\"") "\""))))) (+ "\"" (.replace (cut r 1 -1) "\"" "\\\"") "\"")))))
(hy-repr-register bool str) (hy-repr-register bool str)
(if (not PY3) (hy-repr-register int (fn [x]
(.format "(int {})" (-base-repr x)))))
(if (not PY3) (hy-repr-register long_type (fn [x]
(.rstrip (-base-repr x) "L"))))
(hy-repr-register float (fn [x] (hy-repr-register float (fn [x]
(if (if
(isnan x) "NaN" (isnan x) "NaN"
@ -131,7 +127,7 @@
(-repr-time-innards x)))) (-repr-time-innards x))))
(defn -repr-time-innards [x] (defn -repr-time-innards [x]
(.rstrip (+ " " (.join " " (filter identity [ (.rstrip (+ " " (.join " " (filter identity [
(if x.microsecond (str-type x.microsecond)) (if x.microsecond (str x.microsecond))
(if (not (none? x.tzinfo)) (+ ":tzinfo " (hy-repr x.tzinfo))) (if (not (none? x.tzinfo)) (+ ":tzinfo " (hy-repr x.tzinfo)))
(if (and PY36 (!= x.fold 0)) (+ ":fold " (hy-repr x.fold)))]))))) (if (and PY36 (!= x.fold 0)) (+ ":fold " (hy-repr x.fold)))])))))
(defn -strftime-0 [x fmt] (defn -strftime-0 [x fmt]

View File

@ -11,7 +11,6 @@
(import [fractions [Fraction :as fraction]]) (import [fractions [Fraction :as fraction]])
(import operator) ; shadow not available yet (import operator) ; shadow not available yet
(import sys) (import sys)
(import [hy._compat [long-type]]) ; long for python2, int for python3
(import [hy.models [HySymbol HyKeyword]]) (import [hy.models [HySymbol HyKeyword]])
(import [hy.lex [tokenize mangle unmangle read read-str]]) (import [hy.lex [tokenize mangle unmangle read read-str]])
(import [hy.lex.exceptions [LexException PrematureEndOfInput]]) (import [hy.lex.exceptions [LexException PrematureEndOfInput]])
@ -254,11 +253,11 @@ Return series of accumulated sums (or other binary function results)."
(defn integer [x] (defn integer [x]
"Return Hy kind of integer for `x`." "Return Hy kind of integer for `x`."
(long-type x)) (int x))
(defn integer? [x] (defn integer? [x]
"Check if `x` is an integer." "Check if `x` is an integer."
(isinstance x (, int long-type))) (isinstance x int))
(defn integer-char? [x] (defn integer-char? [x]
"Check if char `x` parses as an integer." "Check if char `x` parses as an integer."

View File

@ -8,7 +8,7 @@ import re
import sys import sys
import unicodedata import unicodedata
from hy._compat import str_type, isidentifier, UCS4 from hy._compat import isidentifier, UCS4
from hy.lex.exceptions import PrematureEndOfInput, LexException # NOQA from hy.lex.exceptions import PrematureEndOfInput, LexException # NOQA
from hy.models import HyExpression, HySymbol from hy.models import HyExpression, HySymbol
@ -116,7 +116,7 @@ def mangle(s):
assert s assert s
s = str_type(s) s = str(s)
s = s.replace("-", "_") s = s.replace("-", "_")
s2 = s.lstrip('_') s2 = s.lstrip('_')
leading_underscores = '_' * (len(s) - len(s2)) leading_underscores = '_' * (len(s) - len(s2))
@ -147,7 +147,7 @@ def unmangle(s):
form. This may not round-trip, because different Hy symbol names can form. This may not round-trip, because different Hy symbol names can
mangle to the same Python identifier.""" mangle to the same Python identifier."""
s = str_type(s) s = str(s)
s2 = s.lstrip('_') s2 = s.lstrip('_')
leading_underscores = len(s) - len(s2) leading_underscores = len(s) - len(s2)
@ -203,4 +203,4 @@ def read(from_file=sys.stdin, eof=""):
def read_str(input): def read_str(input):
return read(StringIO(str_type(input))) return read(StringIO(str(input)))

View File

@ -9,7 +9,6 @@ from functools import wraps
from rply import ParserGenerator from rply import ParserGenerator
from hy._compat import str_type
from hy.models import (HyBytes, HyComplex, HyDict, HyExpression, HyFloat, from hy.models import (HyBytes, HyComplex, HyDict, HyExpression, HyFloat,
HyInteger, HyKeyword, HyList, HySet, HyString, HySymbol) HyInteger, HyKeyword, HyList, HySet, HyString, HySymbol)
from .lexer import lexer from .lexer import lexer
@ -214,7 +213,7 @@ def t_string(state, p):
raise LexException.from_lexer("Can't convert {} to a HyString".format(p[0].value), raise LexException.from_lexer("Can't convert {} to a HyString".format(p[0].value),
state, p[0]) state, p[0])
return (HyString(s, is_format = is_format) return (HyString(s, is_format = is_format)
if isinstance(s, str_type) if isinstance(s, str)
else HyBytes(s)) else HyBytes(s))

View File

@ -9,7 +9,7 @@ import traceback
from contextlib import contextmanager from contextlib import contextmanager
from hy._compat import PY3, string_types, reraise, rename_function from hy._compat import PY3, reraise, rename_function
from hy.models import replace_hy_obj, HyExpression, HySymbol, wrap_value from hy.models import replace_hy_obj, HyExpression, HySymbol, wrap_value
from hy.lex import mangle from hy.lex import mangle
from hy.errors import (HyLanguageError, HyMacroExpansionError, HyTypeError, from hy.errors import (HyLanguageError, HyMacroExpansionError, HyTypeError,
@ -156,7 +156,7 @@ def require(source_module, target_module, assignments, prefix=""):
parent_frame = inspect.stack()[1][0] parent_frame = inspect.stack()[1][0]
target_namespace = parent_frame.f_globals target_namespace = parent_frame.f_globals
target_module = target_namespace.get('__name__', None) target_module = target_namespace.get('__name__', None)
elif isinstance(target_module, string_types): elif isinstance(target_module, str):
target_module = importlib.import_module(target_module) target_module = importlib.import_module(target_module)
target_namespace = target_module.__dict__ target_namespace = target_module.__dict__
elif inspect.ismodule(target_module): elif inspect.ismodule(target_module):

View File

@ -6,7 +6,6 @@ from __future__ import unicode_literals
from contextlib import contextmanager from contextlib import contextmanager
from math import isnan, isinf from math import isnan, isinf
from hy import _initialize_env_var from hy import _initialize_env_var
from hy._compat import PY3, str_type, bytes_type, long_type, string_types
from hy.errors import HyWrapperError from hy.errors import HyWrapperError
from fractions import Fraction from fractions import Fraction
from clint.textui import colored from clint.textui import colored
@ -88,7 +87,7 @@ def repr_indent(obj):
return repr(obj).replace("\n", "\n ") return repr(obj).replace("\n", "\n ")
class HyString(HyObject, str_type): class HyString(HyObject, str):
""" """
Generic Hy String object. Helpful to store string literals from Hy Generic Hy String object. Helpful to store string literals from Hy
scripts. It's either a ``str`` or a ``unicode``, depending on the scripts. It's either a ``str`` or a ``unicode``, depending on the
@ -100,20 +99,20 @@ class HyString(HyObject, str_type):
value.brackets = brackets value.brackets = brackets
return value return value
_wrappers[str_type] = HyString _wrappers[str] = HyString
class HyBytes(HyObject, bytes_type): class HyBytes(HyObject, bytes):
""" """
Generic Hy Bytes object. It's either a ``bytes`` or a ``str``, depending Generic Hy Bytes object. It's either a ``bytes`` or a ``str``, depending
on the Python version. on the Python version.
""" """
pass pass
_wrappers[bytes_type] = HyBytes _wrappers[bytes] = HyBytes
class HySymbol(HyObject, str_type): class HySymbol(HyObject, str):
""" """
Hy Symbol. Basically a string. Hy Symbol. Basically a string.
""" """
@ -170,42 +169,39 @@ def strip_digit_separators(number):
# Don't strip a _ or , if it's the first character, as _42 and # Don't strip a _ or , if it's the first character, as _42 and
# ,42 aren't valid numbers # ,42 aren't valid numbers
return (number[0] + number[1:].replace("_", "").replace(",", "") return (number[0] + number[1:].replace("_", "").replace(",", "")
if isinstance(number, string_types) and len(number) > 1 if isinstance(number, str) and len(number) > 1
else number) else number)
class HyInteger(HyObject, long_type): class HyInteger(HyObject, int):
""" """
Internal representation of a Hy Integer. May raise a ValueError as if Internal representation of a Hy Integer. May raise a ValueError as if
int(foo) was called, given HyInteger(foo). On python 2.x long will int(foo) was called, given HyInteger(foo).
be used instead
""" """
def __new__(cls, number, *args, **kwargs): def __new__(cls, number, *args, **kwargs):
if isinstance(number, string_types): if isinstance(number, str):
number = strip_digit_separators(number) number = strip_digit_separators(number)
bases = {"0x": 16, "0o": 8, "0b": 2} bases = {"0x": 16, "0o": 8, "0b": 2}
for leader, base in bases.items(): for leader, base in bases.items():
if number.startswith(leader): if number.startswith(leader):
# We've got a string, known leader, set base. # We've got a string, known leader, set base.
number = long_type(number, base=base) number = int(number, base=base)
break break
else: else:
# We've got a string, no known leader; base 10. # We've got a string, no known leader; base 10.
number = long_type(number, base=10) number = int(number, base=10)
else: else:
# We've got a non-string; convert straight. # We've got a non-string; convert straight.
number = long_type(number) number = int(number)
return super(HyInteger, cls).__new__(cls, number) return super(HyInteger, cls).__new__(cls, number)
_wrappers[int] = HyInteger _wrappers[int] = HyInteger
if not PY3: # do not add long on python3
_wrappers[long_type] = HyInteger
def check_inf_nan_cap(arg, value): def check_inf_nan_cap(arg, value):
if isinstance(arg, string_types): if isinstance(arg, str):
if isinf(value) and "i" in arg.lower() and "Inf" not in arg: if isinf(value) and "i" in arg.lower() and "Inf" not in arg:
raise ValueError('Inf must be capitalized as "Inf"') raise ValueError('Inf must be capitalized as "Inf"')
if isnan(value) and "NaN" not in arg: if isnan(value) and "NaN" not in arg:
@ -233,7 +229,7 @@ class HyComplex(HyObject, complex):
""" """
def __new__(cls, real, imag=0, *args, **kwargs): def __new__(cls, real, imag=0, *args, **kwargs):
if isinstance(real, string_types): if isinstance(real, str):
value = super(HyComplex, cls).__new__( value = super(HyComplex, cls).__new__(
cls, strip_digit_separators(real) cls, strip_digit_separators(real)
) )

View File

@ -5,14 +5,13 @@
import copy import copy
import hy import hy
from clint.textui.colored import clean from clint.textui.colored import clean
from hy._compat import long_type, str_type
from hy.models import (wrap_value, replace_hy_obj, HyString, HyInteger, HyList, from hy.models import (wrap_value, replace_hy_obj, HyString, HyInteger, HyList,
HyDict, HySet, HyExpression, HyComplex, HyFloat, pretty) HyDict, HySet, HyExpression, HyComplex, HyFloat, pretty)
def test_wrap_long_type(): def test_wrap_int():
""" Test conversion of integers.""" """ Test conversion of integers."""
wrapped = wrap_value(long_type(0)) wrapped = wrap_value(0)
assert type(wrapped) == HyInteger assert type(wrapped) == HyInteger
@ -26,27 +25,27 @@ def test_wrap_tuple():
def test_wrap_nested_expr(): def test_wrap_nested_expr():
""" Test conversion of HyExpressions with embedded non-HyObjects.""" """ Test conversion of HyExpressions with embedded non-HyObjects."""
wrapped = wrap_value(HyExpression([long_type(0)])) wrapped = wrap_value(HyExpression([0]))
assert type(wrapped) == HyExpression assert type(wrapped) == HyExpression
assert type(wrapped[0]) == HyInteger assert type(wrapped[0]) == HyInteger
assert wrapped == HyExpression([HyInteger(0)]) assert wrapped == HyExpression([HyInteger(0)])
def test_replace_long_type(): def test_replace_int():
""" Test replacing integers.""" """ Test replacing integers."""
replaced = replace_hy_obj(long_type(0), HyInteger(13)) replaced = replace_hy_obj(0, HyInteger(13))
assert replaced == HyInteger(0) assert replaced == HyInteger(0)
def test_replace_string_type(): def test_replace_string_type():
"""Test replacing python string""" """Test replacing python string"""
replaced = replace_hy_obj(str_type("foo"), HyString("bar")) replaced = replace_hy_obj("foo", HyString("bar"))
assert replaced == HyString("foo") assert replaced == HyString("foo")
def test_replace_tuple(): def test_replace_tuple():
""" Test replacing tuples.""" """ Test replacing tuples."""
replaced = replace_hy_obj((long_type(0), ), HyInteger(13)) replaced = replace_hy_obj((0, ), HyInteger(13))
assert type(replaced) == HyList assert type(replaced) == HyList
assert type(replaced[0]) == HyInteger assert type(replaced[0]) == HyInteger
assert replaced == HyList([HyInteger(0)]) assert replaced == HyList([HyInteger(0)])