Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mypy: resolve many str-format, has-type, valid-type, var-annotated, valid-type, type-var #2336

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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: 1 addition & 1 deletion AutoDuck/makedfromi.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def GetComments(line, lineNo, lines):


def make_doc_summary(inFile, outFile):
methods = []
methods: list[tuple[str, list[str]]] = []
modDoc = ""
modName = ""
lines = inFile.readlines()
Expand Down
4 changes: 2 additions & 2 deletions AutoDuck/py2d.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ def should_build_function(build_info):

# docstring aware paragraph generator. Isn't there something in docutils
# we can use?
def gen_paras(val):
chunks = []
def gen_paras(val: str):
chunks: list[str] = []
in_docstring = False
for line in val.splitlines():
line = ad_escape(line.strip())
Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/debugger/dbgcon.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def DoGetOption(optsDict, optName, default):


def LoadDebuggerOptions():
opts = {}
opts: dict[str, str] = {}
DoGetOption(opts, OPT_HIDE, 0)
DoGetOption(opts, OPT_STOP_EXCEPTIONS, 1)
return opts
Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/framework/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def ListAllHelpFiles():
def _ListAllHelpFilesInRoot(root):
"""Returns a list of (helpDesc, helpFname) for all registered help files"""

retList = []
retList: list[tuple[str, str]] = []
try:
key = win32api.RegOpenKey(
root, regutil.BuildDefaultPythonKey() + "\\Help", 0, win32con.KEY_READ
Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/framework/interact.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,7 @@ def GetBlockBoundary(self, lineNo):

def ExtractCommand(self, lines):
start, end = lines
retList = []
retList: list[str] = []
while end >= start:
thisLine = self.DoGetLine(end)
promptLen = len(GetPromptPrefix(thisLine))
Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/framework/intpyapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def _SetupSharedMenu_(self):

from pywin.mfc import docview

docview.DocTemplate._SetupSharedMenu_ = _SetupSharedMenu_
docview.DocTemplate._SetupSharedMenu_ = _SetupSharedMenu_ # type: ignore[method-assign]


class MainFrame(app.MainFrame):
Expand Down
14 changes: 6 additions & 8 deletions Pythonwin/pywin/framework/mdi_pychecker.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,18 +61,18 @@ def getsubdirs(d):
class dirpath:
def __init__(self, str, recurse=0):
dp = str.split(";")
dirs = {}
dirs = set()
for d in dp:
if os.path.isdir(d):
d = d.lower()
if d not in dirs:
dirs[d] = None
dirs.add(d)
if recurse:
subdirs = getsubdirs(d)
for sd in subdirs:
sd = sd.lower()
if sd not in dirs:
dirs[sd] = None
dirs.add(sd)
elif os.path.isfile(d):
pass
else:
Expand Down Expand Up @@ -105,16 +105,14 @@ def __init__(self, str, recurse=0):
if x:
for xd in x:
if xd not in dirs:
dirs[xd] = None
dirs.add(xd)
if recurse:
subdirs = getsubdirs(xd)
for sd in subdirs:
sd = sd.lower()
if sd not in dirs:
dirs[sd] = None
self.dirs = []
for d in dirs.keys():
self.dirs.append(d)
dirs.add(sd)
self.dirs = list(dirs)

def __getitem__(self, key):
return self.dirs[key]
Expand Down
7 changes: 3 additions & 4 deletions Pythonwin/pywin/framework/scriptutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ def ImportFile():
# meaning sys.modules can change as a side-effect of looking at
# module.__file__ - so we must take a copy (ie, list(items()))
for key, mod in list(sys.modules.items()):
if getattr(mod, "__file__", None):
if hasattr(mod, "__file__") and mod.__file__:
fname = mod.__file__
base, ext = os.path.splitext(fname)
if ext.lower() in (".pyo", ".pyc"):
Expand Down Expand Up @@ -549,14 +549,13 @@ def RunTabNanny(filename):
data = newout.getvalue()
if data:
try:
lineno = data.split()[1]
lineno = int(lineno)
lineno = int(data.split()[1])
_JumpToPosition(filename, lineno)
try: # Try and display whitespace
GetActiveEditControl().SCISetViewWS(1)
except:
pass
win32ui.SetStatusText("The TabNanny found trouble at line %d" % lineno)
win32ui.SetStatusText(f"The TabNanny found trouble at line {lineno}")
except (IndexError, TypeError, ValueError):
print("The tab nanny complained, but I can't see where!")
print(data)
Expand Down
4 changes: 2 additions & 2 deletions Pythonwin/pywin/framework/winout.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ def __init__(
self.iniSizeSection = None
self.defSize = defSize
self.currentView = None
self.outputQueue = queue.Queue(-1)
self.outputQueue: queue.Queue[str] = queue.Queue(-1)
self.mainThreadId = win32api.GetCurrentThreadId()
self.idleHandlerSet = 0
self.SetIdleHandler()
Expand Down Expand Up @@ -520,7 +520,7 @@ def QueueFlush(self, max=None):
self.currentView.dowrite("".join(items))
return rc

def HandleOutput(self, message):
def HandleOutput(self, message: str):
# debug("QueueOutput on thread %d, flags %d with '%s'...\n" % (win32api.GetCurrentThreadId(), self.writeQueueing, message ))
self.outputQueue.put(message)
if win32api.GetCurrentThreadId() != self.mainThreadId:
Expand Down
8 changes: 3 additions & 5 deletions Pythonwin/pywin/mfc/dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,21 +258,19 @@ def GetSimpleInput(prompt, defValue="", title=None):
# uses a simple dialog to return a string object.
if title is None:
title = win32ui.GetMainFrame().GetWindowText()
# 2to3 insists on converting 'Dialog.__init__' to 'tkinter.dialog...'
DlgBaseClass = Dialog

class DlgSimpleInput(DlgBaseClass):
class DlgSimpleInput(Dialog):
def __init__(self, prompt, defValue, title):
self.title = title
DlgBaseClass.__init__(self, win32ui.IDD_SIMPLE_INPUT)
Dialog.__init__(self, win32ui.IDD_SIMPLE_INPUT)
self.AddDDX(win32ui.IDC_EDIT1, "result")
self.AddDDX(win32ui.IDC_PROMPT1, "prompt")
self._obj_.data["result"] = defValue
self._obj_.data["prompt"] = prompt

def OnInitDialog(self):
self.SetWindowText(self.title)
return DlgBaseClass.OnInitDialog(self)
return Dialog.OnInitDialog(self)

dlg = DlgSimpleInput(prompt, defValue, title)
if dlg.DoModal() != win32con.IDOK:
Expand Down
8 changes: 5 additions & 3 deletions Pythonwin/pywin/scintilla/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
# .py file, and put the config info in a docstring. Then
# pass a CStringIO file (rather than a filename) to the
# config manager.
from __future__ import annotations

import glob
import importlib.util
import marshal
Expand Down Expand Up @@ -35,14 +37,14 @@ def trace(*args):
compiled_config_version = 3


def split_line(line, lineno):
def split_line(line: str, lineno: int):
comment_pos = line.find("#")
if comment_pos >= 0:
line = line[:comment_pos]
sep_pos = line.rfind("=")
if sep_pos == -1:
if line.strip():
print("Warning: Line %d: %s is an invalid entry" % (lineno, repr(line)))
print(f"Warning: Line {lineno}: {line!r} is an invalid entry")
return None, None
return "", ""
return line[:sep_pos].strip(), line[sep_pos + 1 :].strip()
Expand Down Expand Up @@ -271,7 +273,7 @@ def _save_data(self, name, data):
return data

def _load_general(self, sub_section, fp, lineno):
map = {}
map: dict[str, list[str | None]] = {}
while 1:
line, lineno, bBreak = self._readline(fp, lineno)
if bBreak:
Expand Down
18 changes: 7 additions & 11 deletions Pythonwin/pywin/scintilla/view.py
Original file line number Diff line number Diff line change
Expand Up @@ -462,12 +462,6 @@ def SaveTextFile(self, filename, encoding=None):
return 1

def _AutoComplete(self):
def list2dict(l):
ret = {}
for i in l:
ret[i] = None
return ret

self.SCIAutoCCancel() # Cancel old auto-complete lists.
# First try and get an object without evaluating calls
ob = self._GetObjectAtPos(bAllowCalls=0)
Expand All @@ -480,17 +474,19 @@ def list2dict(l):
# extra attributes of win32ui objects
if hasattr(ob, "_obj_"):
try:
items_dict.update(list2dict(dir(ob._obj_)))
items_dict.update(dict.fromkeys(dir(ob._obj_)))
except AttributeError:
pass # object has no __dict__

# normal attributes
try:
items_dict.update(list2dict(dir(ob)))
items_dict.update(dict.fromkeys(dir(ob)))
except AttributeError:
pass # object has no __dict__
if hasattr(ob, "__class__"):
items_dict.update(list2dict(_get_class_attributes(ob.__class__)))
items_dict.update(
dict.fromkeys(_get_class_attributes(ob.__class__))
)
# The object may be a COM object with typelib support - let's see if we can get its props.
# (contributed by Stefan Migowsky)
try:
Expand Down Expand Up @@ -672,8 +668,8 @@ def _GetWordSplit(self, pos=-1, bAllowCalls=0):
if pos == -1:
pos = self.GetSel()[0] - 1 # Character before current one
limit = self.GetTextLength()
before = []
after = []
before: list[str] = []
after: list[str] = []
index = pos - 1
wordbreaks_use = wordbreaks
if bAllowCalls:
Expand Down
2 changes: 1 addition & 1 deletion com/win32com/client/dynamic.py
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,7 @@ def _make_method_(self, name):
# self._print_details_()
codeObject = compile(methodCode, "<COMObject %s>" % self._username_, "exec")
# Exec the code object
tempNameSpace = {}
tempNameSpace: dict[str, object] = {}
# "Dispatch" in the exec'd code is win32com.client.Dispatch, not ours.
globNameSpace = globals().copy()
globNameSpace["Dispatch"] = win32com.client.Dispatch
Expand Down
6 changes: 2 additions & 4 deletions com/win32com/client/gencache.py
Original file line number Diff line number Diff line change
Expand Up @@ -760,10 +760,8 @@ def Rebuild(verbose=1):
def _Dump():
print("Cache is in directory", win32com.__gen_path__)
# Build a unique dir
d = {}
for clsid, (typelibCLSID, lcid, major, minor) in clsidToTypelib.items():
d[typelibCLSID, lcid, major, minor] = None
for typelibCLSID, lcid, major, minor in d.keys():
d = set(clsidToTypelib.values())
for typelibCLSID, lcid, major, minor in d:
mod = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
print(f"{mod.__doc__} - {typelibCLSID}")

Expand Down
6 changes: 4 additions & 2 deletions com/win32comext/axdebug/codecontainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
to color the text, and also how to translate lines into offsets, and back.
"""

from __future__ import annotations

import os
import sys
import tokenize
Expand Down Expand Up @@ -124,7 +126,7 @@ def _ProcessToken(self, type, token, spos, epos, line):
erow, ecol = epos
self.GetText() # Prime us.
linenum = srow - 1 # Lines zero based for us too.
realCharPos = self.lineOffsets[linenum] + scol
realCharPos: int = self.lineOffsets[linenum] + scol
numskipped = realCharPos - self.lastPos
if numskipped == 0:
pass
Expand Down Expand Up @@ -157,7 +159,7 @@ def _ProcessToken(self, type, token, spos, epos, line):

def GetSyntaxColorAttributes(self):
self.lastPos = 0
self.attrs = []
self.attrs: list[tuple[int] | tuple[int, int]] = []
try:
for tokens in tokenize.tokenize(self.GetNextLine):
self._ProcessToken(*tokens)
Expand Down
4 changes: 3 additions & 1 deletion com/win32comext/axscript/client/pyscript.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
command line.
"""

from __future__ import annotations

import re
import types

Expand Down Expand Up @@ -291,7 +293,7 @@ def GetScriptDispatch(self, name):
)
return self.scriptDispatch

def MakeEventMethodName(self, subItemName, eventName):
def MakeEventMethodName(self, subItemName: str, eventName: str):
return (
subItemName[0].upper()
+ subItemName[1:]
Expand Down
20 changes: 18 additions & 2 deletions mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,24 @@ disable_error_code =
misc,
; Name "..." is not defined; (IDEM, leave undefined/unbound to Flake8/Ruff/pyright)
name-defined,
; Cannot assign to a method (we do lots of monkey patching)
method-assign,
; These are the other error codes that would currently fail with check_untyped_defs = true
; TODO: Gradually fix them until we can turn on check_untyped_defs
; arg-type,
; assignment,
; call-arg,
; comparison-overlap,
; has-type,
; index,
; list-item,
; operator,
; override,
; type-var,
; union-attr,
; var-annotated,
; ; And these only happen when checking against types-pywin32
; func-returns-value,
; call-overload,
; no-redef,
exclude = (?x)(
^build/
; Vendored
Expand Down
23 changes: 12 additions & 11 deletions win32/Lib/win32pdhquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,12 @@
"""

# Feb 12, 98 - MH added "rawaddcounter" so caller can get exception details.
from __future__ import annotations

import _thread
import copy
import time
from itertools import chain

import win32api
import win32pdh
Expand Down Expand Up @@ -446,14 +448,11 @@ def getinstpaths(
cur += 1
except IndexError: # if we went over the end
pass
paths = []
for ind in range(len(temp)):
# can this raise an error?
paths.append(
win32pdh.MakeCounterPath(
(machine, "Process", object, None, ind, counter)
)
)
paths = [
win32pdh.MakeCounterPath((machine, "Process", object, None, ind, counter))
for ind in range(len(temp))
]

return paths # should also return the number of elements for naming purposes

def open(self, *args, **namedargs):
Expand All @@ -468,9 +467,11 @@ def open(self, *args, **namedargs):
# do all the normal opening stuff, self._base is now the query object
BaseQuery.open(*(self,) + args, **namedargs)
# should rewrite getinstpaths to take a single tuple
paths = []
for tup in self.volatilecounters:
paths[len(paths) :] = self.getinstpaths(*tup)
paths = list(
chain.from_iterable(
self.getinstpaths(*tup) for tup in self.volatilecounters
)
)
for path in paths:
try:
self.counters.append(win32pdh.AddCounter(self._base, path))
Expand Down
Loading
Loading