Visitar URL original
bpo-41810: Reintroduce `types.EllipsisType`, `.NoneType` & `.NotImplementedType` by BvB93 · Pull Request #22336 · python/cpython · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Revert the type(...) to types.... replacements
Reverts 2791a23 and 0a97a88.
Save this for a follow up.
  • Loading branch information
Bas van Beek
Bas van Beek committed Sep 21, 2020
commit 84ebe183e0c4ed9059e88fbede11092759f3eb66
9 changes: 4 additions & 5 deletions Lib/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
:copyright: Copyright 2008 by Armin Ronacher.
:license: Python License.
"""
import types
import sys
from _ast import *
from contextlib import contextmanager, nullcontext
Expand Down Expand Up @@ -572,22 +571,22 @@ def __new__(cls, *args, **kwargs):
Num: (int, float, complex),
Str: (str,),
Bytes: (bytes,),
NameConstant: (types.NoneType, bool),
Ellipsis: (types.EllipsisType,),
NameConstant: (type(None), bool),
Ellipsis: (type(...),),
}
_const_types_not = {
Num: (bool,),
}

_const_node_type_names = {
bool: 'NameConstant', # should be before int
types.NoneType: 'NameConstant',
type(None): 'NameConstant',
int: 'Num',
float: 'Num',
complex: 'Num',
str: 'Str',
bytes: 'Bytes',
types.EllipsisType: 'Ellipsis',
type(...): 'Ellipsis',
}

class slice(AST):
Expand Down
12 changes: 6 additions & 6 deletions Lib/copy.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,10 @@ def copy(x):

def _copy_immutable(x):
return x
for t in (types.NoneType, int, float, bool, complex, str, tuple,
for t in (type(None), int, float, bool, complex, str, tuple,
bytes, frozenset, type, range, slice, property,
types.BuiltinFunctionType, types.EllipsisType,
types.NotImplementedType, types.FunctionType, weakref.ref):
types.BuiltinFunctionType, type(Ellipsis), type(NotImplemented),
types.FunctionType, weakref.ref):
d[t] = _copy_immutable
t = getattr(types, "CodeType", None)
if t is not None:
Expand Down Expand Up @@ -181,9 +181,9 @@ def deepcopy(x, memo=None, _nil=[]):

def _deepcopy_atomic(x, memo):
return x
d[types.NoneType] = _deepcopy_atomic
d[types.EllipsisType] = _deepcopy_atomic
d[types.NotImplementedType] = _deepcopy_atomic
d[type(None)] = _deepcopy_atomic
d[type(Ellipsis)] = _deepcopy_atomic
d[type(NotImplemented)] = _deepcopy_atomic
d[int] = _deepcopy_atomic
d[float] = _deepcopy_atomic
d[bool] = _deepcopy_atomic
Expand Down
4 changes: 2 additions & 2 deletions Lib/distutils/unixccompiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
* link shared library handled by 'cc -shared'
"""

import os, sys, re, types
import os, sys, re

from distutils import sysconfig
from distutils.dep_util import newer
Expand Down Expand Up @@ -157,7 +157,7 @@ def link(self, target_desc, objects,

lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs,
libraries)
if not isinstance(output_dir, (str, types.NoneType)):
if not isinstance(output_dir, (str, type(None))):
raise TypeError("'output_dir' must be a string or None")
if output_dir is not None:
output_filename = os.path.join(output_dir, output_filename)
Expand Down
3 changes: 1 addition & 2 deletions Lib/idlelib/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import _thread as thread
import threading
import warnings
import types

from idlelib import autocomplete # AutoComplete, fetch_encodings
from idlelib import calltip # Calltip
Expand Down Expand Up @@ -559,7 +558,7 @@ def runcode(self, code):
except SystemExit as e:
if e.args: # SystemExit called with an argument.
ob = e.args[0]
if not isinstance(ob, (types.NoneType, int)):
if not isinstance(ob, (type(None), int)):
print('SystemExit: ' + str(ob), file=sys.stderr)
# Return to the interactive prompt.
except:
Expand Down
2 changes: 1 addition & 1 deletion Lib/imp.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ def find_module(name, path=None):
"""
if not isinstance(name, str):
raise TypeError("'name' must be a str, not {}".format(type(name)))
elif not isinstance(path, (types.NoneType, list)):
elif not isinstance(path, (type(None), list)):
# Backwards-compatibility
raise RuntimeError("'path' must be None or a list, "
"not {}".format(type(path)))
Expand Down
2 changes: 1 addition & 1 deletion Lib/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -2034,7 +2034,7 @@ def wrap_value(s):
except NameError:
raise RuntimeError()

if isinstance(value, (str, int, float, bytes, bool, types.NoneType)):
if isinstance(value, (str, int, float, bytes, bool, type(None))):
return ast.Constant(value)
raise RuntimeError()

Expand Down
3 changes: 3 additions & 0 deletions Lib/lib2to3/fixes/fix_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,15 @@
'ComplexType' : 'complex',
'DictType': 'dict',
'DictionaryType' : 'dict',
'EllipsisType' : 'type(Ellipsis)',
#'FileType' : 'io.IOBase',
'FloatType': 'float',
'IntType': 'int',
'ListType': 'list',
'LongType': 'int',
'ObjectType' : 'object',
'NoneType': 'type(None)',
'NotImplementedType' : 'type(NotImplemented)',
'SliceType' : 'slice',
'StringType': 'bytes', # XXX ?
'StringTypes' : '(str,)', # XXX ?
Expand Down
4 changes: 4 additions & 0 deletions Lib/lib2to3/tests/test_fixers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3276,6 +3276,10 @@ def test_basic_types_convert(self):
a = """int"""
self.check(b, a)

b = """types.NoneType"""
a = """type(None)"""
self.check(b, a)

b = "types.StringTypes"
a = "(str,)"
self.check(b, a)
Expand Down
12 changes: 6 additions & 6 deletions Lib/pickle.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

"""

import types
from types import FunctionType
from copyreg import dispatch_table
from copyreg import _extension_registry, _inverted_registry, _extension_cache
from itertools import islice
Expand Down Expand Up @@ -737,7 +737,7 @@ def save_reduce(self, func, args, state=None, listitems=None,

def save_none(self, obj):
self.write(NONE)
dispatch[types.NoneType] = save_none
dispatch[type(None)] = save_none

def save_bool(self, obj):
if self.proto >= 2:
Expand Down Expand Up @@ -1117,15 +1117,15 @@ def save_global(self, obj, name=None):
self.memoize(obj)

def save_type(self, obj):
if obj is types.NoneType:
if obj is type(None):
return self.save_reduce(type, (None,), obj=obj)
elif obj is types.NotImplementedType:
elif obj is type(NotImplemented):
return self.save_reduce(type, (NotImplemented,), obj=obj)
elif obj is types.EllipsisType:
elif obj is type(...):
return self.save_reduce(type, (...,), obj=obj)
return self.save_global(obj)

dispatch[types.FunctionType] = save_global
dispatch[FunctionType] = save_global
dispatch[type] = save_type


Expand Down
3 changes: 1 addition & 2 deletions Lib/pickletools.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import pickle
import re
import sys
import types

__all__ = ['dis', 'genops', 'optimize']

Expand Down Expand Up @@ -1018,7 +1017,7 @@ def __repr__(self):

pynone = StackObject(
name="None",
obtype=types.NoneType,
obtype=type(None),
doc="The Python None object.")

pytuple = StackObject(
Expand Down
2 changes: 1 addition & 1 deletion Lib/pprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -591,7 +591,7 @@ def _safe_repr(object, context, maxlevels, level, sort_dicts):
return rep, (rep and not rep.startswith('<')), False

_builtin_scalars = frozenset({str, bytes, bytearray, int, float, complex,
bool, _types.NoneType})
bool, type(None)})

def _recursion(object):
return ("<Recursion on %s with id=%s>"
Expand Down
2 changes: 1 addition & 1 deletion Lib/pydoc_data/topics.py
Original file line number Diff line number Diff line change
Expand Up @@ -1365,7 +1365,7 @@
'explicitly return a\n'
'value. It supports no special operations. There is '
'exactly one null\n'
'object, named "None" (a built-in name). "types.NoneType()" '
'object, named "None" (a built-in name). "type(None)()" '
'produces the\n'
'same singleton.\n'
'\n'
Expand Down
3 changes: 1 addition & 2 deletions Lib/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@
from bisect import bisect as _bisect
import os as _os
import _random
import types

try:
# hashlib is pretty heavy to load, try lean internal module first
Expand Down Expand Up @@ -155,7 +154,7 @@ def seed(self, a=None, version=2):
a += _sha512(a).digest()
a = int.from_bytes(a, 'big')

elif not isinstance(a, (types.NoneType, int, float, str, bytes, bytearray)):
elif not isinstance(a, (type(None), int, float, str, bytes, bytearray)):
_warn('Seeding based on hashing is deprecated\n'
'since Python 3.9 and will be removed in a subsequent '
'version. The only \n'
Expand Down
2 changes: 1 addition & 1 deletion Lib/runpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ def run_path(path_name, init_globals=None, run_name=None):
if type(importer).__module__ == 'imp':
if type(importer).__name__ == 'NullImporter':
is_NullImporter = True
if isinstance(importer, types.NoneType) or is_NullImporter:
if isinstance(importer, type(None)) or is_NullImporter:
# Not a valid sys.path entry, so run the code directly
# execfile() doesn't help as we want to allow compiled files
code, fname = _get_code_from_file(run_name, path_name)
Expand Down
9 changes: 4 additions & 5 deletions Lib/sqlite3/test/userfunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
# misrepresented as being the original software.
# 3. This notice may not be removed or altered from any source distribution.

import types
import unittest
import unittest.mock
import sqlite3 as sqlite
Expand Down Expand Up @@ -50,7 +49,7 @@ def func_isint(v):
def func_isfloat(v):
return type(v) is float
def func_isnone(v):
return type(v) is types.NoneType
return type(v) is type(None)
def func_isblob(v):
return isinstance(v, (bytes, memoryview))
def func_islonglong(v):
Expand Down Expand Up @@ -108,7 +107,7 @@ def __init__(self):
self.val = None

def step(self, whichType, val):
theType = {"str": str, "int": int, "float": float, "None": types.NoneType,
theType = {"str": str, "int": int, "float": float, "None": type(None),
"blob": bytes}
self.val = int(theType[whichType] is type(val))

Expand All @@ -120,7 +119,7 @@ def __init__(self):
self.val = 0

def step(self, whichType, *vals):
theType = {"str": str, "int": int, "float": float, "None": types.NoneType,
theType = {"str": str, "int": int, "float": float, "None": type(None),
"blob": bytes}
for val in vals:
self.val += int(theType[whichType] is type(val))
Expand Down Expand Up @@ -212,7 +211,7 @@ def CheckFuncReturnNull(self):
cur = self.con.cursor()
cur.execute("select returnnull()")
val = cur.fetchone()[0]
self.assertEqual(type(val), types.NoneType)
self.assertEqual(type(val), type(None))
self.assertEqual(val, None)

def CheckFuncReturnBlob(self):
Expand Down
5 changes: 2 additions & 3 deletions Lib/test/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import inspect
import builtins
import unittest
import types
from unittest.mock import Mock
from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional
from typing import get_type_hints
Expand Down Expand Up @@ -2027,7 +2026,7 @@ class C:
def test_docstring_one_field_with_default_none(self):
@dataclass
class C:
x: Union[int, types.NoneType] = None
x: Union[int, type(None)] = None

self.assertDocStrEqual(C.__doc__, "C(x:Optional[int]=None)")

Expand Down Expand Up @@ -2956,7 +2955,7 @@ def test_text_annotations(self):
self.assertEqual(
get_type_hints(dataclass_textanno.Bar.__init__),
{'foo': dataclass_textanno.Foo,
'return': types.NoneType})
'return': type(None)})


class TestMakeDataclass(unittest.TestCase):
Expand Down
22 changes: 11 additions & 11 deletions Lib/test/test_descr.py
Original file line number Diff line number Diff line change
Expand Up @@ -3260,7 +3260,7 @@ class Int(int): __slots__ = []
cant(2, bool)
o = object()
cant(o, type(1))
cant(o, types.NoneType)
cant(o, type(None))
del o
class G(object):
__slots__ = ["a", "b"]
Expand Down Expand Up @@ -4000,35 +4000,35 @@ class D(C):

def test_unsubclassable_types(self):
with self.assertRaises(TypeError):
class X(types.NoneType):
class X(type(None)):
pass
with self.assertRaises(TypeError):
class X(object, types.NoneType):
class X(object, type(None)):
pass
with self.assertRaises(TypeError):
class X(types.NoneType, object):
class X(type(None), object):
pass
class O(object):
pass
with self.assertRaises(TypeError):
class X(O, types.NoneType):
class X(O, type(None)):
pass
with self.assertRaises(TypeError):
class X(types.NoneType, O):
class X(type(None), O):
pass

class X(object):
pass
with self.assertRaises(TypeError):
X.__bases__ = types.NoneType,
X.__bases__ = type(None),
with self.assertRaises(TypeError):
X.__bases__ = object, types.NoneType
X.__bases__ = object, type(None)
with self.assertRaises(TypeError):
X.__bases__ = types.NoneType, object
X.__bases__ = type(None), object
with self.assertRaises(TypeError):
X.__bases__ = O, types.NoneType
X.__bases__ = O, type(None)
with self.assertRaises(TypeError):
X.__bases__ = types.NoneType, O
X.__bases__ = type(None), O

def test_mutable_bases_with_failing_mro(self):
# Testing mutable bases with failing mro...
Expand Down
Loading