Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 2 additions & 0 deletions Include/cpython/dictobject.h
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,5 @@ PyAPI_FUNC(int) PyDict_Unwatch(int watcher_id, PyObject* dict);

// Create a frozendict. Create an empty dictionary if iterable is NULL.
PyAPI_FUNC(PyObject*) PyFrozenDict_New(PyObject *iterable);

PyAPI_FUNC(PyObject*) PyDict_AsFrozenDictAndClear(PyObject *obj);
6 changes: 3 additions & 3 deletions Lib/_pyrepl/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,7 @@ def _build_source_lines(
pos -= line_len + 1
current_offset += line_len + (1 if has_newline else 0)

return tuple(source_lines)
return source_lines.take_tuple()

def _build_content_lines(
self,
Expand Down Expand Up @@ -559,7 +559,7 @@ def _build_content_lines(
),
)
)
return tuple(content_lines)
return content_lines.take_tuple()

def _layout_content(
self,
Expand Down Expand Up @@ -596,7 +596,7 @@ def _render_message_lines(self) -> tuple[RenderLine, ...]:
render_lines.append(
RenderLine.from_rendered_text(message_line[offset : offset + width])
)
return tuple(render_lines)
return render_lines.take_tuple()

def get_screen_overlays(self) -> tuple[ScreenOverlay, ...]:
return ()
Expand Down
4 changes: 2 additions & 2 deletions Lib/_pyrepl/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def append_plain_text(segment: str) -> None:
if pending_controls:
cells.append(RenderCell("", 0, controls=tuple(pending_controls)))

return tuple(cells)
return cells.take_tuple()


@dataclass(frozen=True, slots=True)
Expand Down Expand Up @@ -219,7 +219,7 @@ def _compose(self) -> tuple[RenderLine, ...]:
lines.extend([EMPTY_RENDER_LINE] * (target_len - len(lines)))
for index, line in enumerate(overlay.lines):
lines[adjusted_y + index] = line
return tuple(lines)
return lines.take_tuple()

@classmethod
def empty(cls) -> Self:
Expand Down
10 changes: 5 additions & 5 deletions Lib/_pyrepl/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@
ANSI_ESCAPE_SEQUENCE = re.compile(r"\x1b\[[ -@]*[A-~]")
ZERO_WIDTH_BRACKET = re.compile(r"\x01.*?\x02")
ZERO_WIDTH_TRANS = str.maketrans({"\x01": "", "\x02": ""})
IDENTIFIERS_AFTER = frozenset({"def", "class"})
KEYWORD_CONSTANTS = frozenset({"True", "False", "None"})
BUILTINS = frozenset({str(name) for name in dir(builtins) if not name.startswith('_')})
IDENTIFIERS_AFTER = {"def", "class"}.take_frozenset()
KEYWORD_CONSTANTS = {"True", "False", "None"}.take_frozenset()
BUILTINS = {str(name) for name in dir(builtins) if not name.startswith('_')}.take_frozenset()


def THEME(**kwargs):
Expand Down Expand Up @@ -243,8 +243,8 @@ def gen_colors_from_token_stream(
yield ColorSpan(span, "builtin")


keyword_first_sets_match = frozenset({"False", "None", "True", "await", "lambda", "not"})
keyword_first_sets_case = frozenset({"False", "None", "True"})
keyword_first_sets_match = {"False", "None", "True", "await", "lambda", "not"}.take_frozenset()
keyword_first_sets_case = {"False", "None", "True"}.take_frozenset()


def is_soft_keyword_used(*tokens: TI | None) -> bool:
Expand Down
5 changes: 5 additions & 0 deletions Lib/_weakrefset.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,8 @@ def __repr__(self):
return repr(self.data)

__class_getitem__ = classmethod(GenericAlias)

def take_frozenset(self):
frozen = frozenset(self)
self.clear()
return frozen
2 changes: 1 addition & 1 deletion Lib/annotationlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -875,7 +875,7 @@ def _build_closure(annotate, owner, is_class, stringifier_dict, *, allow_evaluat
stringifier_dict.stringifiers.append(fwdref)
new_cell = types.CellType(fwdref)
new_closure.append(new_cell)
return tuple(new_closure), cell_dict
return new_closure.take_tuple(), cell_dict


def _stringify_single(anno):
Expand Down
10 changes: 10 additions & 0 deletions Lib/collections/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1274,6 +1274,11 @@ def fromkeys(cls, iterable, value=None):
d[key] = value
return d

def take_frozendict(self):
result = frozendict(self)
self.clear()
return result


################################################################################
### UserList
Expand Down Expand Up @@ -1407,6 +1412,11 @@ def extend(self, other):
else:
self.data.extend(other)

def take_tuple(self):
result = tuple(self)
self.clear()
return result


################################################################################
### UserString
Expand Down
2 changes: 1 addition & 1 deletion Lib/copy.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ def _deepcopy_frozendict(x, memo, deepcopy=deepcopy):
return memo[id(x)]
except KeyError:
pass
return frozendict(y)
return y.take_frozendict()
d[frozendict] = _deepcopy_frozendict

def _deepcopy_method(x, memo): # Copy instance methods
Expand Down
4 changes: 2 additions & 2 deletions Lib/curses/has_key.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

# Table mapping curses keys to the terminfo capability name

_capability_names = frozendict({
_capability_names = {
_curses.KEY_A1: 'ka1',
_curses.KEY_A3: 'ka3',
_curses.KEY_B2: 'kb2',
Expand Down Expand Up @@ -157,7 +157,7 @@
_curses.KEY_SUSPEND: 'kspd',
_curses.KEY_UNDO: 'kund',
_curses.KEY_UP: 'kcuu1'
})
}.take_frozendict()

def has_key(ch):
if isinstance(ch, str):
Expand Down
2 changes: 1 addition & 1 deletion Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -1538,7 +1538,7 @@ def _asdict_inner(obj, dict_factory):
for k, v in obj.items()
}
elif obj_type is tuple:
return tuple([_asdict_inner(v, dict_factory) for v in obj])
return [_asdict_inner(v, dict_factory) for v in obj].take_tuple()
elif issubclass(obj_type, tuple):
if hasattr(obj, '_fields'):
# obj is a namedtuple. Recurse into it, but the returned
Expand Down
4 changes: 2 additions & 2 deletions Lib/functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ def _lt_from_ge(self, other):
return op_result
return not op_result

_convert = frozendict({
_convert = {
'__lt__': [('__gt__', _gt_from_lt),
('__le__', _le_from_lt),
('__ge__', _ge_from_lt)],
Expand All @@ -183,7 +183,7 @@ def _lt_from_ge(self, other):
'__ge__': [('__le__', _le_from_ge),
('__gt__', _gt_from_ge),
('__lt__', _lt_from_ge)]
})
}.take_frozendict()

def total_ordering(cls):
"""Class decorator that fills in missing ordering methods"""
Expand Down
4 changes: 2 additions & 2 deletions Lib/getpass.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class GetPassWarning(UserWarning): pass


# Default POSIX control character mappings
_POSIX_CTRL_CHARS = frozendict({
_POSIX_CTRL_CHARS = {
'BS': '\x08', # Backspace
'ERASE': '\x7f', # DEL
'KILL': '\x15', # Ctrl+U - kill line
Expand All @@ -38,7 +38,7 @@ class GetPassWarning(UserWarning): pass
'SOH': '\x01', # Ctrl+A - start of heading (beginning of line)
'ENQ': '\x05', # Ctrl+E - enquiry (end of line)
'VT': '\x0b', # Ctrl+K - vertical tab (kill forward)
})
}.take_frozendict()


def _get_terminal_ctrl_chars(fd):
Expand Down
6 changes: 3 additions & 3 deletions Lib/gettext.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,9 @@ def _error(value):
('+', '-'),
('*', '/', '%'),
)
_binary_ops = frozendict({op: i for i, ops in enumerate(_binary_ops, 1)
for op in ops})
_c2py_ops = frozendict({'||': 'or', '&&': 'and', '/': '//'})
_binary_ops = {op: i for i, ops in enumerate(_binary_ops, 1)
for op in ops}.take_frozendict()
_c2py_ops = {'||': 'or', '&&': 'and', '/': '//'}.take_frozendict()


def _parse(tokens, priority=-1):
Expand Down
2 changes: 1 addition & 1 deletion Lib/idlelib/hyperparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def get_surrounding_brackets(self, openers='([{', mustclose=False):

# the set of built-in identifiers which are also keywords,
# i.e. keyword.iskeyword() returns True for them
_ID_KEYWORDS = frozenset({"True", "False", "None"})
_ID_KEYWORDS = {"True", "False", "None"}.take_frozenset()

@classmethod
def _eat_identifier(cls, str, limit, pos):
Expand Down
2 changes: 1 addition & 1 deletion Lib/imaplib.py
Original file line number Diff line number Diff line change
Expand Up @@ -2101,7 +2101,7 @@ def ParseFlags(resp):
if not mo:
return ()

return tuple(mo.group('flags').split())
return mo.group('flags').split().take_tuple()


def Time2Internaldate(date_time):
Expand Down
2 changes: 1 addition & 1 deletion Lib/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -2873,7 +2873,7 @@ def args(self):
# plain argument
args.append(arg)

return tuple(args)
return args.take_tuple()

@property
def kwargs(self):
Expand Down
4 changes: 2 additions & 2 deletions Lib/json/decoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ def __reduce__(self):
return self.__class__, (self.msg, self.doc, self.pos)


_CONSTANTS = frozendict({
_CONSTANTS = {
'-Infinity': NegInf,
'Infinity': PosInf,
'NaN': NaN,
})
}.take_frozendict()


HEXDIGITS = re.compile(r'[0-9A-Fa-f]{4}', FLAGS)
Expand Down
4 changes: 2 additions & 2 deletions Lib/json/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@
(?P<null>null)
''', re.VERBOSE)

_group_to_theme_color = frozendict({
_group_to_theme_color = {
"key": "definition",
"string": "string",
"number": "number",
"boolean": "keyword",
"null": "keyword",
})
}.take_frozendict()


def _colorize_json(json_str, theme):
Expand Down
4 changes: 2 additions & 2 deletions Lib/multiprocessing/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -874,8 +874,8 @@ def PipeClient(address):
# of the opening challenge or length of the returned digest as a signal as
# to which protocol the other end supports.

_ALLOWED_DIGESTS = frozenset(
{b'md5', b'sha256', b'sha384', b'sha3_256', b'sha3_384'})
_ALLOWED_DIGESTS = (
{b'md5', b'sha256', b'sha384', b'sha3_256', b'sha3_384'}.take_frozenset())
_MAX_DIGEST_LEN = max(len(_) for _ in _ALLOWED_DIGESTS)

# Old hmac-md5 only server versions from Python <=3.11 sent a message of this
Expand Down
6 changes: 3 additions & 3 deletions Lib/optparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -407,12 +407,12 @@ def _parse_num(val, type):
def _parse_int(val):
return _parse_num(val, int)

_builtin_cvt = frozendict({
_builtin_cvt = {
"int": (_parse_int, _("integer")),
"long": (_parse_int, _("integer")),
"float": (float, _("floating-point")),
"complex": (complex, _("complex")),
})
}.take_frozendict()

def check_builtin(option, opt, value):
(cvt, what) = _builtin_cvt[option.type]
Expand Down Expand Up @@ -760,7 +760,7 @@ def convert_value(self, opt, value):
if self.nargs == 1:
return self.check_value(opt, value)
else:
return tuple([self.check_value(opt, v) for v in value])
return [self.check_value(opt, v) for v in value].take_tuple()

def process(self, opt, value, values, parser):

Expand Down
2 changes: 1 addition & 1 deletion Lib/pathlib/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ def parents(self):
parents.append(self.with_segments(parent))
path = parent
parent = split(path)[0]
return tuple(parents)
return parents.take_tuple()

def relative_to(self, other, *, walk_up=False):
"""Return the relative path to another path identified by the passed
Expand Down
4 changes: 2 additions & 2 deletions Lib/pickletools.py
Original file line number Diff line number Diff line change
Expand Up @@ -2229,11 +2229,11 @@ def __init__(self, name, code, arg,
op_meta=frozenset({"BINPERSID", "FRAME", "MARK", "PERSID", "PROTO"}),
op_stack=frozenset({"DUP", "POP", "POP_MARK", "STOP"}),
)
_opcode_color_attr = frozendict({
_opcode_color_attr = {
name: attr
for attr, names in _opcode_categories.items()
for name in names
})
}.take_frozendict()
assert _opcode_color_attr.keys() <= name2i.keys(), (
f"unknown opcodes: {_opcode_color_attr.keys() - name2i.keys()}"
)
Expand Down
12 changes: 6 additions & 6 deletions Lib/platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@
# Based on the description of the PHP's version_compare():
# http://php.net/manual/en/function.version-compare.php

_ver_stages = frozendict({
_ver_stages = {
# any string not found in this dict, will get 0 assigned
'dev': 10,
'alpha': 20, 'a': 20,
Expand All @@ -136,7 +136,7 @@
'RC': 50, 'rc': 50,
# number, will get 100 assigned
'pl': 200, 'p': 200,
})
}.take_frozendict()


def _comparable_version(version):
Expand Down Expand Up @@ -181,7 +181,7 @@ def libc_ver(executable=None, lib='', version='', chunksize=16384):
# parse 'glibc 2.28' as ('glibc', '2.28')
parts = ver.split(maxsplit=1)
if len(parts) == 2:
return tuple(parts)
return parts.take_tuple()
except (AttributeError, ValueError, OSError):
# os.confstr() or CS_GNU_LIBC_VERSION value not available
pass
Expand Down Expand Up @@ -705,11 +705,11 @@ def _syscmd_file(target, default=''):

# Default values for architecture; non-empty strings override the
# defaults given as parameters
_default_architecture = frozendict({
_default_architecture = {
'win32': ('', 'WindowsPE'),
'win16': ('', 'Windows'),
'dos': ('', 'MSDOS'),
})
}.take_frozendict()

def architecture(executable=sys.executable, bits='', linkage=''):

Expand Down Expand Up @@ -1208,7 +1208,7 @@ def python_version_tuple():
will always include the patchlevel (it defaults to 0).

"""
return tuple(_sys_version()[1].split('.'))
return _sys_version()[1].split('.').take_tuple()

def python_branch():

Expand Down
6 changes: 3 additions & 3 deletions Lib/plistlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ class InvalidFileException (ValueError):
def __init__(self, message="Invalid file"):
ValueError.__init__(self, message)

_BINARY_FORMAT = frozendict({1: 'B', 2: 'H', 4: 'L', 8: 'Q'})
_BINARY_FORMAT = {1: 'B', 2: 'H', 4: 'L', 8: 'Q'}.take_frozendict()

_undefined = object()

Expand Down Expand Up @@ -869,7 +869,7 @@ def _is_fmt_binary(header):
# Generic bits
#

_FORMATS=frozendict({
_FORMATS={
FMT_XML: frozendict(
detect=_is_fmt_xml,
parser=_PlistParser,
Expand All @@ -880,7 +880,7 @@ def _is_fmt_binary(header):
parser=_BinaryPlistParser,
writer=_BinaryPlistWriter,
)
})
}.take_frozendict()


def load(fp, *, fmt=None, dict_type=dict, aware_datetime=False):
Expand Down
Loading
Loading