Skip to content
Merged
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
21 changes: 18 additions & 3 deletions IPython/core/interactiveshell.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@
from IPython.display import display
from IPython.paths import get_ipython_dir
from IPython.testing.skipdoctest import skip_doctest
from IPython.utils import PyColorize, io, openpy, py3compat
from IPython.utils import PyColorize, io, openpy
from IPython.utils.decorators import undoc
from IPython.utils.io import ask_yes_no
from IPython.utils.ipstruct import Struct
Expand Down Expand Up @@ -2866,11 +2866,19 @@ def _user_obj_error(self):
etype, evalue, tb = self._get_exc_info()
stb = self.InteractiveTB.get_exception_only(etype, evalue)

try:
evalue_str = str(evalue)
except UnicodeError:
try:
evalue_str = repr(evalue)
except UnicodeError:
evalue_str = "Unrecoverably corrupt evalue"

exc_info = {
"status": "error",
"traceback": stb,
"ename": etype.__name__,
"evalue": py3compat.safe_unicode(evalue),
"evalue": evalue_str,
}

return exc_info
Expand Down Expand Up @@ -2974,10 +2982,17 @@ def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False
# Python inserts the script's directory into sys.path
dname = str(fname.parent)

def execfile(fname, glob, loc=None, compiler=None):
__tracebackhide__ = "__ipython_bottom__"
loc = loc if (loc is not None) else glob
with open(fname, "rb") as f:
compiler = compiler or compile
exec(compiler(f.read(), fname, "exec"), glob, loc)

with prepended_to_syspath(dname), self.builtin_trap:
try:
glob, loc = (where + (None, ))[:2]
py3compat.execfile(
execfile(
fname, glob, loc,
self.compile if shell_futures else None)
except SystemExit as status:
Expand Down
3 changes: 1 addition & 2 deletions IPython/core/page.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
from IPython.utils.data import chop
from IPython.utils.process import system
from IPython.utils.terminal import get_terminal_size
from IPython.utils import py3compat


def display_page(strng, start=0, screen_lines=25):
Expand Down Expand Up @@ -340,7 +339,7 @@ def page_more():
return result
else:
def page_more():
ans = py3compat.input('---Return to continue, q to quit--- ')
ans = input('---Return to continue, q to quit--- ')
if ans.lower().startswith('q'):
return False
else:
Expand Down
7 changes: 3 additions & 4 deletions IPython/core/tbtools.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
from IPython import get_ipython
from IPython.core import debugger
from IPython.utils import path as util_path
from IPython.utils import py3compat
from IPython.utils.PyColorize import Theme, TokenStream, theme_table

_sentinel = object()
Expand Down Expand Up @@ -180,6 +179,7 @@ def _tokens_filename(
em: wether bold or not
file : str
"""
assert file is None or isinstance(file, str)
Normal = Token.NormalEm if em else Token.Normal
Filename = Token.FilenameEm if em else Token.Filename
ipinst = get_ipython()
Expand All @@ -202,9 +202,8 @@ def _tokens_filename(
(Filename, f", line {lineno}"),
]
else:
name = util_path.compress_user(
py3compat.cast_unicode(file or "", util_path.fs_encoding)
)
file_str = file or ""
name = util_path.compress_user(file_str)
if lineno is None:
Comment on lines +205 to 207

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@claude it look like file can never be bytes; remove the conditional; add an assertion at the start of the function.

return [
(Normal, "File "),
Expand Down
10 changes: 5 additions & 5 deletions IPython/lib/clipboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import subprocess

from IPython.core.error import TryNext
import IPython.utils.py3compat as py3compat
from IPython.utils.encoding import DEFAULT_ENCODING


class ClipboardEmpty(ValueError):
Expand All @@ -28,7 +28,7 @@ def win32_clipboard_get():
except (TypeError, win32clipboard.error):
try:
text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT)
text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
text = text if isinstance(text, str) else text.decode(DEFAULT_ENCODING, "replace")
except (TypeError, win32clipboard.error) as e:
raise ClipboardEmpty from e
finally:
Expand All @@ -44,7 +44,7 @@ def osx_clipboard_get() -> str:
bytes_, stderr = p.communicate()
# Text comes in with old Mac \r line endings. Change them to \n.
bytes_ = bytes_.replace(b'\r', b'\n')
text = py3compat.decode(bytes_)
text = bytes_.decode(DEFAULT_ENCODING, "replace")
return text


Expand All @@ -68,7 +68,7 @@ def tkinter_clipboard_get():
raise ClipboardEmpty from e
finally:
root.destroy()
text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
text = text if isinstance(text, str) else text.decode(DEFAULT_ENCODING, "replace")
return text


Expand All @@ -95,7 +95,7 @@ def wayland_clipboard_get():
raise ClipboardEmpty

try:
text = py3compat.decode(raw)
text = raw.decode(DEFAULT_ENCODING, "replace")
except UnicodeDecodeError as e:
raise ClipboardEmpty from e

Expand Down
5 changes: 2 additions & 3 deletions IPython/lib/demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,6 @@

from IPython.utils.text import marquee
from IPython.utils import openpy
from IPython.utils import py3compat
__all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']

class DemoError(Exception): pass
Expand Down Expand Up @@ -475,7 +474,7 @@ def __call__(self,index=None):
print(marquee('output:'))
else:
print(marquee('Press <q> to quit, <Enter> to execute...'), end=' ')
ans = py3compat.input().strip()
ans = input().strip()
if ans:
print(marquee('Block NOT executed'))
return
Expand Down Expand Up @@ -643,7 +642,7 @@ def slide(file_path, noclear=False, format_rst=True, formatter="terminal",
while not demo.finished:
demo()
try:
py3compat.input('\n' + delimiter)
input('\n' + delimiter)
except KeyboardInterrupt:
exit(1)

Expand Down
3 changes: 1 addition & 2 deletions IPython/lib/editorhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@

from IPython import get_ipython
from IPython.core.error import TryNext
from IPython.utils import py3compat


def install_editor(template, wait=False):
Expand Down Expand Up @@ -55,7 +54,7 @@ def call_editor(self, filename, line=0):
if proc.wait() != 0:
raise TryNext()
if wait:
py3compat.input("Press Enter when done editing:")
input("Press Enter when done editing:")

get_ipython().set_hook('editor', call_editor)
get_ipython().editor = template
Expand Down
5 changes: 2 additions & 3 deletions IPython/lib/pretty.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,15 +96,14 @@ def _repr_pretty_(self, p, cycle):
from contextlib import contextmanager
import datetime
import os
import platform
import re
import sys
import types
from collections import deque
from inspect import signature
from io import StringIO

from IPython.utils.py3compat import PYPY

from typing import Dict

# Allow pretty-printing of functions with PEP-649 annotations
Expand Down Expand Up @@ -708,7 +707,7 @@ def _super_pprint(obj, p, cycle):
p.pretty(obj.__thisclass__)
p.text(',')
p.breakable()
if PYPY: # In PyPy, super() objects don't have __self__ attributes
if platform.python_implementation() == "PyPy": # In PyPy, super() objects don't have __self__ attributes
dself = obj.__repr__.__self__
p.pretty(None if dself is obj else dself)
else:
Expand Down
1 change: 0 additions & 1 deletion IPython/terminal/interactiveshell.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
display_formatter_default_active_types,
terminal_default_mime_renderers,
)
from IPython.utils.py3compat import input
from IPython.utils.PyColorize import theme_table
from IPython.utils.terminal import toggle_set_term_title, set_term_title, restore_term_title
from IPython.utils.process import abbrev_cwd
Expand Down
3 changes: 1 addition & 2 deletions IPython/terminal/magics.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@
from IPython.lib.clipboard import ClipboardEmpty
from IPython.testing.skipdoctest import skip_doctest
from IPython.utils.text import SList, strip_email_quotes
from IPython.utils import py3compat

def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False):
def get_pasted_lines(sentinel, l_input=input, quiet=False):
""" Yield pasted lines until the user enters the given sentinel value.
"""
if not quiet:
Expand Down
6 changes: 3 additions & 3 deletions IPython/testing/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from traitlets.config.loader import Config
from IPython.utils.process import get_output_error_code
from IPython.utils.io import temp_pyfile, Tee
from IPython.utils import py3compat
from IPython.utils.encoding import DEFAULT_ENCODING

from . import decorators as dec
from . import skipdoctest
Expand Down Expand Up @@ -207,8 +207,8 @@ def ipexec(fname: str, options: list[str] | None=None, commands: tuple[str, ...]
if not isinstance(v, str):
print(k, v)
p = Popen(full_cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE, env=env)
out, err = p.communicate(input=py3compat.encode('\n'.join(commands)) or None)
out, err = py3compat.decode(out), py3compat.decode(err)
out, err = p.communicate(input=('\n'.join(commands).encode(DEFAULT_ENCODING, "replace")) or None)
out, err = out.decode(DEFAULT_ENCODING, "replace"), err.decode(DEFAULT_ENCODING, "replace")
# `import readline` causes 'ESC[?1034h' to be output sometimes,
# so strip that out before doing comparisons
if out:
Expand Down
6 changes: 3 additions & 3 deletions IPython/utils/_process_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

_T = TypeVar("_T")

from IPython.utils import py3compat
from .encoding import DEFAULT_ENCODING

#-----------------------------------------------------------------------------
# Function definitions
Expand Down Expand Up @@ -140,7 +140,7 @@ def getoutput(cmd: str | list[str]) -> str:
out = process_handler(cmd, lambda p: p.communicate()[0], subprocess.STDOUT)
if out is None:
return ''
return py3compat.decode(out)
return out.decode(DEFAULT_ENCODING, "replace")


def getoutputerror(cmd: str | list[str]) -> tuple[str, str]:
Expand Down Expand Up @@ -183,7 +183,7 @@ def get_output_error_code(cmd: str | list[str]) -> tuple[str, str, int | None]:
if result is None:
return '', '', None
(out, err), p = result
return py3compat.decode(out), py3compat.decode(err), p.returncode
return out.decode(DEFAULT_ENCODING, "replace"), err.decode(DEFAULT_ENCODING, "replace"), p.returncode

def arg_split(commandline: str, posix: bool = False, strict: bool = True) -> list[str]:
"""Split a command line's arguments in a shell-like manner.
Expand Down
3 changes: 1 addition & 2 deletions IPython/utils/_process_win32.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
from types import TracebackType
from typing import List, Optional

from . import py3compat
from ._process_common import arg_split as py_arg_split

from ._process_common import process_handler, read_no_interrupt
Expand Down Expand Up @@ -156,7 +155,7 @@ def getoutput(cmd: str) -> str:

if out is None:
out = b""
return py3compat.decode(out)
return out.decode(DEFAULT_ENCODING, "replace")


try:
Expand Down
60 changes: 0 additions & 60 deletions IPython/utils/py3compat.py

This file was deleted.

15 changes: 11 additions & 4 deletions tests/test_debugger.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,19 @@
from IPython.core import debugger
from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE
from IPython.testing.decorators import skip_win32
from IPython.utils import py3compat
import pytest

# -----------------------------------------------------------------------------
# Helper for executing files with proper debugger frame marking
def execfile(fname, glob, loc=None, compiler=None):
__tracebackhide__ = "__ipython_bottom__"
loc = loc if (loc is not None) else glob
with open(fname, "rb") as f:
compiler_fn = compiler or compile
exec(compiler_fn(f.read(), fname, "exec"), glob, loc)


# Helper classes, from CPython's Pdb test suite
# -----------------------------------------------------------------------------
#


class _FakeInput(object):
Expand Down Expand Up @@ -304,7 +311,7 @@ def test_execfile_marks_debugger_internal_frames_hidden():
)

with pytest.raises(RuntimeError) as exc_info:
py3compat.execfile(script, {})
execfile(script, {})

ipdb = debugger.Pdb()
stack, _ = ipdb.get_stack(None, exc_info.value.__traceback__)
Expand Down
Loading