Skip to content

tkinter Tk.readprofile reads profile scripts with the locale default encoding #153333

Description

@tonghuaroot

Bug report

Tk.readprofile execs the user's ~/.CLASSNAME.py and ~/.BASENAME.py
profile scripts, read with open(...) and no encoding argument in
Lib/tkinter/__init__.py. The source is therefore decoded with the locale
default encoding.

This emits an EncodingWarning under -X warn_default_encoding, and on a
non-UTF-8 locale (for example Windows cp1252) it mis-decodes a profile whose
source is UTF-8 or carries a PEP 263 coding cookie. The same bare
open(...).read() also leaks the file descriptor until garbage collection.

It is the only unspecified-encoding open() in Lib/tkinter.

Reproduction

Create ~/.Foo.py with a coding cookie and a non-ASCII value:

# -*- coding: latin-1 -*-
self.profile_result = 'caf\xe9'

then, under -X warn_default_encoding:

import tkinter
root = tkinter.Tk()
root.readprofile('foo', 'Foo')

The open(class_py).read() in readprofile raises
EncodingWarning: 'encoding' argument not specified under
-W error::EncodingWarning, and on a UTF-8 locale fails on the Latin-1 byte.

Fix

Read the profile scripts with tokenize.open(), which decodes using the
encoding detected from the file (its PEP 263 coding cookie, else UTF-8), the
correct encoding for reading Python source. The context-manager form also
closes the file promptly. A gui-gated regression test is included.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions