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

Fix undefined names reported by Flake8/Ruff #2101

Merged
merged 12 commits into from
Apr 9, 2024
8 changes: 4 additions & 4 deletions Pythonwin/pywin/Demos/cmdserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,10 @@ def ServerThread(myout, cmd, title, bCloseOnEnd):

# assist for reloading (when debugging) - use only 1 tracer object,
# else a large chain of tracer objects will exist.
# try:
# writer
# except NameError:
# writer=ThreadWriter()
try:
writer
except NameError:
writer = ThreadWriter()
if __name__ == "__main__":
import demoutils

Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/Demos/fontdemo.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def SetFont(self, new_font):
# Change font on the fly
self.font = win32ui.CreateFont(new_font)
# redraw the entire client window
selfInvalidateRect(None)
self.InvalidateRect(None)

def OnSize(self, params):
lParam = params[3]
Expand Down
25 changes: 17 additions & 8 deletions Pythonwin/pywin/Demos/ocx/msoffice.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,9 @@
import win32con
import win32ui
import win32uiole
from pywin.mfc import docview, object, window
from pywin.mfc import activex, docview, object, window
from win32com.client import gencache

# WordModule = gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 1033, 8, 0)
# if WordModule is None:
# raise ImportError, "Microsoft Word version 8 does not appear to be installed."


class OleClientItem(object.CmdTarget):
def __init__(self, doc):
Expand Down Expand Up @@ -122,6 +118,18 @@ def __init__(self, doc=None):
# Dont call base class doc/view version...

def Create(self, title, rect=None, parent=None):
WordModule = gencache.EnsureModule(
"{00020905-0000-0000-C000-000000000046}", 1033, 8, 0
)
if WordModule is None:
raise ImportError(
"Microsoft Word version 8 does not appear to be installed."
)

# WordModule.Word doesn't exist in WordModule, WordModule.Words does, but CreateControl still fails
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

We could either leave this as-is if we'd like to fix it later (the calling code is still commented out, at least now tooling won't report undefined names / unbound variables).

Or delete the WordFrame class entirely (doesn't look like this part of the demo was ever run in the git history)

class MyWordControl(activex.Control, WordModule.Word):
...

style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_OVERLAPPEDWINDOW
self._obj_.CreateWindow(None, title, style, rect, parent)

Expand All @@ -141,11 +149,12 @@ def Demo():
docName = None
if len(sys.argv) > 1:
docName = win32api.GetFullPathName(sys.argv[1])
OleTemplate().OpenDocumentFile(None)
OleTemplate().OpenDocumentFile(docName)
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

That or remove the option to provide docName (which was unused)


# ActiveX not currently working
# f = WordFrame(docName)
# f.Create("Microsoft Office")

# f = WordFrame(docName)
# f.Create("Microsoft Office")

if __name__ == "__main__":
Demo()
6 changes: 0 additions & 6 deletions Pythonwin/pywin/Demos/ocx/ocxtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,12 +228,6 @@ def test2():
d = None


def test3():
d = TestCOMMDialog(MakeDlgTemplate())
d.DoModal()
d = None


def testall():
test1()
test2()
Expand Down
6 changes: 0 additions & 6 deletions Pythonwin/pywin/debugger/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
import sys


# Some cruft to deal with the Pythonwin GUI booting up from a non GUI app.
def _MakeDebuggerGUI():
app.InitInstance()


isInprocApp = -1


Expand Down
8 changes: 4 additions & 4 deletions Pythonwin/pywin/dialogs/ideoptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,25 +115,25 @@ def OnFormatTitle(self, command, code):
fmt = self.GetFormat(interact.formatTitle)
if fmt:
formatTitle = fmt
SaveFontPreferences()
interact.SaveFontPreferences()

def OnFormatInput(self, command, code):
global formatInput
fmt = self.GetFormat(formatInput)
if fmt:
formatInput = fmt
SaveFontPreferences()
interact.SaveFontPreferences()

def OnFormatOutput(self, command, code):
global formatOutput
fmt = self.GetFormat(formatOutput)
if fmt:
formatOutput = fmt
SaveFontPreferences()
interact.SaveFontPreferences()

def OnFormatError(self, command, code):
global formatOutputError
fmt = self.GetFormat(formatOutputError)
if fmt:
formatOutputError = fmt
SaveFontPreferences()
interact.SaveFontPreferences()
4 changes: 3 additions & 1 deletion Pythonwin/pywin/framework/dlgappcore.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,14 @@ def OnInitDialog(self):
def OnPaint(self):
if not self.IsIconic():
return self._obj_.OnPaint()
dc, paintStruct = self.BeginPaint()
self.DefWindowProc(win32con.WM_ICONERASEBKGND, dc.GetHandleOutput(), 0)
left, top, right, bottom = self.GetClientRect()
left = (right - win32api.GetSystemMetrics(win32con.SM_CXICON)) >> 1
top = (bottom - win32api.GetSystemMetrics(win32con.SM_CYICON)) >> 1
hIcon = win32ui.GetApp().LoadIcon(self.iconId)
self.GetDC().DrawIcon((left, top), hIcon)
dc.DrawIcon((left, top), hIcon)
self.EndPaint(paintStruct)

# Only needed to provide a minimized icon (and this seems
# less important under win95/NT4
Expand Down
11 changes: 10 additions & 1 deletion Pythonwin/pywin/framework/interact.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,15 @@ def SavePreference(prefName, prefValue):
win32ui.WriteProfileVal(sectionProfile, prefName, prefValue)


def SaveFontPreferences():
win32ui.WriteProfileVal(sectionProfile, valueFormatTitle, str(formatTitle))
win32ui.WriteProfileVal(sectionProfile, valueFormatInput, str(formatInput))
win32ui.WriteProfileVal(sectionProfile, valueFormatOutput, str(formatOutput))
win32ui.WriteProfileVal(
sectionProfile, valueFormatOutputError, str(formatOutputError)
)


def GetPromptPrefix(line):
ps1 = sys.ps1
if line[: len(ps1)] == ps1:
Expand Down Expand Up @@ -333,7 +342,7 @@ def Init(self):
)
)
else:
sys.stderr.write(banner)
sys.stderr.write(self.banner)
rcfile = os.environ.get("PYTHONSTARTUP")
if rcfile:
import __main__
Expand Down
1 change: 1 addition & 0 deletions Pythonwin/pywin/framework/mdi_pychecker.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import re
import sys
import time
from functools import reduce

import win32api
import win32con
Expand Down
4 changes: 2 additions & 2 deletions Pythonwin/pywin/scintilla/configui.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ def OnOK(self):


def test():
page = ColorEditorPropertyPage()
sheet = pywin.mfc.dialog.PropertySheet("Test")
page = ScintillaFormatPropertyPage()
sheet = dialog.PropertySheet("Test")
sheet.AddPage(page)
sheet.CreateWindow()
18 changes: 0 additions & 18 deletions Pythonwin/pywin/scintilla/scintillacon.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,5 @@
# Generated by h2py from Include\scintilla.h
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I'd be curious in how to regenerate this file. It could give more insights on why there's undefined names here.

Copy link
Owner

Choose a reason for hiding this comment

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

There used to be a "h2py.py" file which came with Python - I've no idea if it still does, or if not, what happened to it.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Removed in Python 3.9
Original issue: https://bugs.python.org/issue37704
GitHub issue: python/cpython#81885
GitHub PR: python/cpython#15000
Last version of the script before removal (no new commits between the 3.8 and 3.9 tag, other than removal): https://github.com/python/cpython/blob/3.8/Tools/scripts/h2py.py

Copy link
Collaborator Author

@Avasam Avasam Feb 8, 2024

Choose a reason for hiding this comment

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

Alright so, long story short: These "undefined names" in files generated by h2py have always been like this (meaning broken and unusable) so removing them doesn't hurt.

They are generated like that because h2py does string manipulation on c header files, then tries to evaluate the statements. Methods can successfully be defined in python even if the symbol doesn't exists (lazy evalution), so these get added to the generated python file.
The "undefined names" are mostly C casts or other C macros.


For posterity: Some files I've been able to regenerate nearly seamlessly (other than the manual stuff added), some are even improved, others are a complete mess.



# Included from BaseTsd.h
def HandleToUlong(h):
return HandleToULong(h)


def UlongToHandle(ul):
return ULongToHandle(ul)


def UlongToPtr(ul):
return ULongToPtr(ul)


def UintToPtr(ui):
return UIntToPtr(ui)


INVALID_POSITION = -1
SCI_START = 2000
SCI_OPTIONAL_START = 3000
Expand Down
10 changes: 5 additions & 5 deletions Pythonwin/pywin/tools/TraceCollector.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ def _StopThread(self):
def Close(self):
self._StopThread()
winout.WindowOutput.Close(self)
# def OnViewDestroy(self, frame):
# return winout.WindowOutput.OnViewDestroy(self, frame)
# def Create(self, title=None, style = None):
# rc = winout.WindowOutput.Create(self, title, style)
return rc
# def OnViewDestroy(self, frame):
# return winout.WindowOutput.OnViewDestroy(self, frame)
# def Create(self, title=None, style = None):
# rc = winout.WindowOutput.Create(self, title, style)
# return rc


def MakeOutputWindow():
Expand Down
2 changes: 1 addition & 1 deletion com/win32com/readme.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ <h3>VARIANT objects</h3>
Up until build 212, code could set <code>pythoncom.__future_currency__ = True</code>
to force use of the decimal module, with a warning issued otherwise. In
builds 213 and later, the decimal module is unconditionally used when
pythoncon returns you a currency value.
pythoncom returns you a currency value.
</p>

<h3>Recent Changes</h3>
Expand Down
3 changes: 2 additions & 1 deletion com/win32com/server/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
from sys import exc_info

import pythoncom
import pywin.debugger
import pywin.debugger.dbgcon
import win32api
import win32com
from win32com.server.exception import IsCOMServerException
Expand Down Expand Up @@ -257,7 +259,6 @@ def _HandleException_(self):
"""Invoke the debugger post mortem capability"""
# Save details away.
typ, val, tb = exc_info()
# import pywin.debugger, pywin.debugger.dbgcon
debug = 0
try:
raise typ(val)
Expand Down
2 changes: 1 addition & 1 deletion com/win32com/server/exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def IsCOMException(t=None):
try:
return issubclass(t, pythoncom.com_error)
except TypeError: # 1.5 in -X mode?
Avasam marked this conversation as resolved.
Show resolved Hide resolved
return t is pythoncon.com_error
return t is pythoncom.com_error


def IsCOMServerException(t=None):
Expand Down
1 change: 1 addition & 0 deletions com/win32com/test/daodump.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# import dao3032
# No longer imported here - callers responsibility to load
#
import pythoncom
import win32com.client


Expand Down
3 changes: 1 addition & 2 deletions com/win32com/test/testClipboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,7 @@ def QueryGetData(self, fe):
return None # should check better

def GetCanonicalFormatEtc(self, fe):
RaiseCOMException(winerror.DATA_S_SAMEFORMATETC)
# return fe
raise COMException(winerror.DATA_S_SAMEFORMATETC)

def SetData(self, fe, medium):
raise COMException(hresult=winerror.E_NOTIMPL)
Expand Down
2 changes: 1 addition & 1 deletion com/win32com/test/testGatewayAddresses.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class Dummy2:
]


class DeletgatedDummy:
class DelegatedDummy:
_public_methods_ = []


Expand Down
1 change: 1 addition & 0 deletions com/win32com/test/testvb.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#

import traceback
from collections.abc import Callable

import pythoncom
import win32com.client
Expand Down
1 change: 1 addition & 0 deletions com/win32comext/adsi/demos/test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import sys
from collections.abc import Callable

import pythoncom
import win32api
Expand Down
14 changes: 8 additions & 6 deletions com/win32comext/axscript/client/pydumper.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
# as a scripting language - meaning the dumps produced can be quite dynamic,
# and based on the script code you execute.

import sys

import win32api
import win32con
from win32com.axscript import axscript

from . import pyscript
Expand All @@ -34,8 +38,6 @@ class PyScript(pyscript.PyScript):


def Register():
import sys

if "-d" in sys.argv:
dispatcher = "DispatcherWin32trace"
debug_desc = " (" + dispatcher + ")"
Expand All @@ -51,7 +53,7 @@ def Register():
policy = None # "win32com.axscript.client.axspolicy.AXScriptPolicy"

print("Registering COM server%s..." % debug_desc)
from win32com.server.register import RegisterServer
from win32com.server.register import RegisterServer, _set_string

languageName = "PyDump"
verProgId = "Python.Dumper.1"
Expand All @@ -66,10 +68,10 @@ def Register():
dispatcher=dispatcher,
)

CreateRegKey(languageName + "\\OLEScript")
win32api.RegCreateKey(win32con.HKEY_CLASSES_ROOT, languageName + "\\OLEScript")
# Basic Registration for wsh.
win32com.server.register._set_string(".pysDump", "pysDumpFile")
win32com.server.register._set_string("pysDumpFile\\ScriptEngine", languageName)
_set_string(".pysDump", "pysDumpFile")
_set_string("pysDumpFile\\ScriptEngine", languageName)
print("Dumping Server registered.")


Expand Down
2 changes: 1 addition & 1 deletion com/win32comext/shell/demos/servers/context_menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def QueryContextMenu(self, hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags):
elif uFlags & shellcon.CMF_EXPLORE:
print("CMF_EXPLORE...")
items.append(msg + " - normal file, right-click in Explorer")
elif uFlags & CMF_DEFAULTONLY:
elif uFlags & shellcon.CMF_DEFAULTONLY:
print("CMF_DEFAULTONLY...\r\n")
else:
print("** unknown flags", uFlags)
Expand Down
2 changes: 1 addition & 1 deletion com/win32comext/shell/demos/servers/shell_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -849,7 +849,7 @@ def CreateViewWindow(self, prev, settings, browser, rect):
}
# win32gui.SetWindowLong(self.hwnd, win32con.GWL_WNDPROC, message_map)

file_data = file(self.filename, "U").read()
file_data = open(self.filename, "U").read()

self._SetupLexer()
self._SendSci(scintillacon.SCI_ADDTEXT, len(file_data), file_data)
Expand Down
4 changes: 2 additions & 2 deletions isapi/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,8 @@ def GetWebServer(description=None):
def LoadWebServer(path):
try:
server = GetObject(path)
except pythoncom.com_error as details:
msg = details.strerror
except pythoncom.com_error as exc:
msg = exc.strerror
if exc.excepinfo and exc.excepinfo[2]:
msg = exc.excepinfo[2]
msg = f"WebServer {path}: {msg}"
Expand Down
1 change: 1 addition & 0 deletions pywin32_postinstall.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#
# copies PyWinTypesxx.dll and PythonCOMxx.dll into the system directory,
# and creates a pth file
import argparse
import glob
import os
import shutil
Expand Down
Loading