Skip to content

Commit

Permalink
some more typing
Browse files Browse the repository at this point in the history
  • Loading branch information
Carreau committed Oct 26, 2023
1 parent e3a70dc commit 71bfc9d
Show file tree
Hide file tree
Showing 6 changed files with 40 additions and 31 deletions.
3 changes: 2 additions & 1 deletion IPython/core/completerlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,8 @@ def try_import(mod: str, only_modules=False) -> List[str]:
completions.extend(m_all)

if m_is_init:
completions.extend(module_list(os.path.dirname(m.__file__)))
file_ = m.__file__
completions.extend(module_list(os.path.dirname(file_)))
completions_set = {c for c in completions if isinstance(c, str)}
completions_set.discard('__init__')
return list(completions_set)
Expand Down
9 changes: 5 additions & 4 deletions IPython/core/inputsplitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
import tokenize
import warnings

from typing import List, Tuple, Union
from typing import List, Tuple, Union, Optional
from types import CodeType

from IPython.core.inputtransformer import (leading_indent,
classic_prompt,
Expand Down Expand Up @@ -336,7 +337,7 @@ class InputSplitter(object):
# Code object corresponding to the current source. It is automatically
# synced to the source, so it can be queried at any time to obtain the code
# object; it will be None if the source doesn't compile to valid Python.
code = None
code:Optional[CodeType] = None

# Private attributes

Expand All @@ -345,9 +346,9 @@ class InputSplitter(object):
# Command compiler
_compile: codeop.CommandCompiler
# Boolean indicating whether the current block is complete
_is_complete = None
_is_complete:Optional[bool] = None
# Boolean indicating whether the current block has an unrecoverable syntax error
_is_invalid = False
_is_invalid:bool = False

def __init__(self) -> None:
"""Create a new InputSplitter instance."""
Expand Down
28 changes: 15 additions & 13 deletions IPython/core/inputtransformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def wrap(cls, func):
"""
@functools.wraps(func)
def transformer_factory(**kwargs):
return cls(func, **kwargs)
return cls(func, **kwargs) # type: ignore [call-arg]

return transformer_factory

Expand Down Expand Up @@ -194,7 +194,7 @@ def assemble_logical_lines():
line = ''.join(parts)

# Utilities
def _make_help_call(target, esc, lspace):
def _make_help_call(target:str, esc:str, lspace:str) -> str:
"""Prepares a pinfo(2)/psearch call from a target name and the escape
(i.e. ? or ??)"""
method = 'pinfo2' if esc == '??' \
Expand All @@ -212,25 +212,25 @@ def _make_help_call(target, esc, lspace):


# These define the transformations for the different escape characters.
def _tr_system(line_info):
def _tr_system(line_info:LineInfo):
"Translate lines escaped with: !"
cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
return '%sget_ipython().system(%r)' % (line_info.pre, cmd)

def _tr_system2(line_info):
def _tr_system2(line_info:LineInfo):
"Translate lines escaped with: !!"
cmd = line_info.line.lstrip()[2:]
return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd)

def _tr_help(line_info):
def _tr_help(line_info:LineInfo):
"Translate lines escaped with: ?/??"
# A naked help line should just fire the intro help screen
if not line_info.line[1:]:
return 'get_ipython().show_usage()'

return _make_help_call(line_info.ifun, line_info.esc, line_info.pre)

def _tr_magic(line_info):
def _tr_magic(line_info:LineInfo):
"Translate lines escaped with: %"
tpl = '%sget_ipython().run_line_magic(%r, %r)'
if line_info.line.startswith(ESC_MAGIC2):
Expand All @@ -241,17 +241,17 @@ def _tr_magic(line_info):
t_magic_name = t_magic_name.lstrip(ESC_MAGIC)
return tpl % (line_info.pre, t_magic_name, t_magic_arg_s)

def _tr_quote(line_info):
def _tr_quote(line_info:LineInfo):
"Translate lines escaped with: ,"
return '%s%s("%s")' % (line_info.pre, line_info.ifun,
'", "'.join(line_info.the_rest.split()) )

def _tr_quote2(line_info):
def _tr_quote2(line_info:LineInfo):
"Translate lines escaped with: ;"
return '%s%s("%s")' % (line_info.pre, line_info.ifun,
line_info.the_rest)

def _tr_paren(line_info):
def _tr_paren(line_info:LineInfo):
"Translate lines escaped with: /"
return '%s%s(%s)' % (line_info.pre, line_info.ifun,
", ".join(line_info.the_rest.split()))
Expand All @@ -266,7 +266,7 @@ def _tr_paren(line_info):
ESC_PAREN : _tr_paren }

@StatelessInputTransformer.wrap
def escaped_commands(line):
def escaped_commands(line:str):
"""Transform escaped commands - %magic, !system, ?help + various autocalls.
"""
if not line or line.isspace():
Expand Down Expand Up @@ -342,20 +342,22 @@ def ends_in_comment_or_string(src):


@StatelessInputTransformer.wrap
def help_end(line):
def help_end(line:str):
"""Translate lines with ?/?? at the end"""
m = _help_end_re.search(line)
if m is None or ends_in_comment_or_string(line):
return line
target = m.group(1)
esc = m.group(3)
lspace = _initial_space_re.match(line).group(0)
match = _initial_space_re.match(line)
assert match is not None
lspace = match.group(0)

return _make_help_call(target, esc, lspace)


@CoroutineInputTransformer.wrap
def cellmagic(end_on_blank_line=False):
def cellmagic(end_on_blank_line:bool=False):
"""Captures & transforms cell magics.
After a cell magic is started, this stores up any lines it gets until it is
Expand Down
11 changes: 7 additions & 4 deletions IPython/utils/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
from string import Formatter
from pathlib import Path

from typing import List, Union, Optional, Dict, Tuple


class LSString(str):
"""String derivative with a special access attributes.
Expand Down Expand Up @@ -627,7 +629,7 @@ def _col_chunks(l, max_rows, row_first=False):
yield l[i:(i + max_rows)]


def _find_optimal(rlist, row_first=False, separator_size=2, displaywidth=80):
def _find_optimal(rlist, row_first:bool, separator_size:int, displaywidth:int):
"""Calculate optimal info to columnize a list of string"""
for max_rows in range(1, len(rlist) + 1):
col_widths = list(map(max, _col_chunks(rlist, max_rows, row_first)))
Expand All @@ -650,7 +652,7 @@ def _get_or_default(mylist, i, default=None):
return mylist[i]


def compute_item_matrix(items, row_first=False, empty=None, *args, **kwargs) :
def compute_item_matrix(items, row_first:bool=False, empty=None,*, separator_size=2, displaywidth=80) -> Tuple[List[List[int]], Dict[str, int]] :
"""Returns a nested list, and info to columnize items
Parameters
Expand Down Expand Up @@ -705,7 +707,7 @@ def compute_item_matrix(items, row_first=False, empty=None, *args, **kwargs) :
stacklevel=2,
category=PendingDeprecationWarning,
)
info = _find_optimal(list(map(len, items)), row_first, *args, **kwargs)
info = _find_optimal(list(map(len, items)), row_first, separator_size=separator_size, displaywidth=displaywidth)
nrow, ncol = info['max_rows'], info['num_columns']
if row_first:
return ([[_get_or_default(items, r * ncol + c, default=empty) for c in range(ncol)] for r in range(nrow)], info)
Expand Down Expand Up @@ -741,10 +743,11 @@ def columnize(items, row_first=False, separator=" ", displaywidth=80, spread=Fa
)
if not items:
return '\n'
matrix:List[List[int]]
matrix, info = compute_item_matrix(items, row_first=row_first, separator_size=len(separator), displaywidth=displaywidth)
if spread:
separator = separator.ljust(int(info['optimal_separator_width']))
fmatrix = [filter(None, x) for x in matrix]
fmatrix:List[filter[int]] = [filter(None, x) for x in matrix]
sjoin = lambda x : separator.join([ y.ljust(w, ' ') for y, w in zip(x, info['column_widths'])])
return '\n'.join(map(sjoin, fmatrix))+'\n'

Expand Down
4 changes: 2 additions & 2 deletions IPython/utils/timing.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
# If possible (Unix), use the resource module instead of time.clock()
try:
import resource
except ImportError:
resource = None
except ModuleNotFoundError:
resource = None #type: ignore [assignment]

# Some implementations (like jyputerlite) don't have getrusage
if resource is not None and hasattr(resource, "getrusage"):
Expand Down
16 changes: 9 additions & 7 deletions IPython/utils/tokenutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@
from keyword import iskeyword

import tokenize
from tokenize import TokenInfo
from typing import List, Optional


Token = namedtuple('Token', ['token', 'text', 'start', 'end', 'line'])

def generate_tokens(readline):
"""wrap generate_tokens to catch EOF errors"""
"""wrap generate_tkens to catch EOF errors"""
try:
for token in tokenize.generate_tokens(readline):
yield token
Expand All @@ -22,7 +24,7 @@ def generate_tokens(readline):
return


def generate_tokens_catch_errors(readline, extra_errors_to_catch=None):
def generate_tokens_catch_errors(readline, extra_errors_to_catch:Optional[List[str]]=None):
default_errors_to_catch = [
"unterminated string literal",
"invalid non-printable character",
Expand All @@ -31,7 +33,7 @@ def generate_tokens_catch_errors(readline, extra_errors_to_catch=None):
assert extra_errors_to_catch is None or isinstance(extra_errors_to_catch, list)
errors_to_catch = default_errors_to_catch + (extra_errors_to_catch or [])

tokens = []
tokens:List[TokenInfo] = []
try:
for token in tokenize.generate_tokens(readline):
tokens.append(token)
Expand Down Expand Up @@ -84,7 +86,7 @@ def line_at_cursor(cell, cursor_pos=0):
line = ""
return (line, offset)

def token_at_cursor(cell, cursor_pos=0):
def token_at_cursor(cell:str, cursor_pos:int=0):
"""Get the token at a given cursor
Used for introspection.
Expand All @@ -94,13 +96,13 @@ def token_at_cursor(cell, cursor_pos=0):
Parameters
----------
cell : unicode
cell : str
A block of Python code
cursor_pos : int
The location of the cursor in the block where the token should be found
"""
names = []
tokens = []
names:List[str] = []
tokens:List[Token] = []
call_names = []

offsets = {1: 0} # lines start at 1
Expand Down

0 comments on commit 71bfc9d

Please sign in to comment.