python / python/cpython

tokenize.detect_encoding has issues with \r

Open
#93,608 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib type-bug
Dominant language
Python
Stars
77.2k
Forks
36k
Avg merge
1d 9h
Merged PRs (30d)
558

Description

Tokenize does not correctly detect encodings when the carriage return character is involved. In this program, it does not detect the header, since it does not consider the \r to start a new line.

import tokenize
import runpy

code = """\r# coding: big5

print('錯誤的答案')
"""

with open('file.py', 'w', encoding='big5') as file:
    file.write(code)
with open('file.py', 'rb') as file:
    print(tokenize.detect_encoding(file.readline))
    # result: ('utf-8', [b'\r# coding: big5\r\n', b'\r\n'])

runpy.run_path('file.py')
# prints 錯誤的答案 as required

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue names tokenize.detect_encoding and provides a complete carriage-return reproduction. Start by running the supplied script, then locate the encoding-detection implementation and existing tests; done means the coding header is detected as big5 when \r precedes it, with regression coverage for this input.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.