Skip to content

Commit

Permalink
chore: typing
Browse files Browse the repository at this point in the history
  • Loading branch information
phil65 committed Oct 22, 2024
1 parent a5affd1 commit 1568d7d
Show file tree
Hide file tree
Showing 30 changed files with 233 additions and 204 deletions.
17 changes: 11 additions & 6 deletions prettyqt/animations/fx.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ def animate(
) -> AnimationTimer:
"""General animation with global coordinates."""
self._animation = core.PropertyAnimation()
self._animation.apply_to(self._widget.__getattr__(self._property_name))
prop = getattr(self._widget, self._property_name)
self._animation.apply_to(prop)
self._animation.set_start_value(start)
self._animation.set_end_value(end)
self._animation.set_easing(easing)
Expand All @@ -75,7 +76,8 @@ def transition_to(
) -> AnimationTimer:
"""Makes property transition from current value to given end value."""
self._animation = core.PropertyAnimation()
self._animation.apply_to(self._widget.__getattr__(self._property_name))
prop = getattr(self._widget, self._property_name)
self._animation.apply_to(prop)
prop_name = self._animation.get_property_name()
obj = self._animation.targetObject()
start: datatypes.VariantType = obj.property(prop_name)
Expand Down Expand Up @@ -106,7 +108,8 @@ def transition_from(
) -> AnimationTimer:
"""Makes property transition from given start value to its current value."""
self._animation = core.PropertyAnimation()
self._animation.apply_to(self._widget.__getattr__(self._property_name))
prop = getattr(self._widget, self._property_name)
self._animation.apply_to(prop)
prop_name = self._animation.get_property_name()
obj = self._animation.targetObject()
end: core.VariantType = obj.property(prop_name)
Expand Down Expand Up @@ -137,7 +140,8 @@ def animate_on_event(
) -> core.PropertyAnimation:
"""Starts property transition from start to end when given event occurs."""
self._animation = core.PropertyAnimation()
self._animation.apply_to(self._widget.__getattr__(self._property_name))
prop = getattr(self._widget, self._property_name)
self._animation.apply_to(prop)
if start is None:
prop_name = self._animation.get_property_name()
obj = self._animation.targetObject()
Expand Down Expand Up @@ -174,8 +178,9 @@ def __init__(self, widget: widgets.QWidget):
def __getitem__(self, value: str) -> AnimationWrapper:
value = helpers.to_lower_camel(value)
logger.debug(f"Building {value!r} PropertyAnimation for {self._widget!r}")
self._wrapper = AnimationWrapper(value, self)
return self._wrapper
wrapper = AnimationWrapper(value, self)
self._wrapper = wrapper
return wrapper

# def __getattr__(self, attr):
# return self.__getitem__(attr)
Expand Down
4 changes: 2 additions & 2 deletions prettyqt/charts/boxset.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def __getitem__(
self, index: int | ValuePositionStr | QtCharts.QBoxSet.ValuePositions
) -> float:
"""Returns the value of the box-and-whiskers item specified by index."""
if type(index) is not int: # noqa: E721
if type(index) is not int:
index = VALUE_POSITION.get_enum_value(index).value
if not (0 <= index <= 4):
raise KeyError(index)
Expand All @@ -46,7 +46,7 @@ def __setitem__(
self, index: int | ValuePositionStr | QtCharts.QBoxSet.ValuePositions, value: int
):
"""Sets the value specified by value in the position specified by index."""
if type(index) is not int: # noqa: E721
if type(index) is not int:
index = VALUE_POSITION.get_enum_value(index).value
if not (0 <= index <= 4):
raise KeyError(index)
Expand Down
7 changes: 4 additions & 3 deletions prettyqt/core/_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ class DateTime(core.QDateTime):
"""DateTime funcitons."""

def __repr__(self):
template = super().__repr__().split("(")[1]
super_repr = super().__repr__()
template = str(super_repr).split("(")[1]
return f"{type(self).__name__}({template}"

def __str__(self):
Expand All @@ -19,9 +20,9 @@ def __str__(self):
def __reduce__(self):
return type(self), (self.date(), self.time(), self.get_timezone())

def __format__(self, format_spec: constants.DateFormatStr):
def __format__(self, format_spec: str):
if format_spec in constants.DATE_FORMAT:
return self.to_format(format_spec)
return self.toString(constants.DATE_FORMAT[format_spec])
return self.toString(format_spec)

@classmethod
Expand Down
3 changes: 2 additions & 1 deletion prettyqt/core/_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ class Time(core.QTime):
"""Clock time functions."""

def __repr__(self):
template = super().__repr__().split("(")[1] # type: ignore
super_repr = super().__repr__()
template = str(super_repr).split("(")[1] # type: ignore
return f"{type(self).__name__}({template}"

def __str__(self):
Expand Down
2 changes: 1 addition & 1 deletion prettyqt/core/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@
z_order_change=mod.Type.ZOrderChange,
)

MouseButtonTypeStr = Literal["press", "release", "double_click", "release"]
MouseButtonTypeStr = Literal["press", "release", "double_click", "move"]

MouseButtonType: bidict[MouseButtonTypeStr, QtCore.QEvent.Type] = bidict(
press=QtCore.QEvent.Type.MouseButtonPress,
Expand Down
4 changes: 3 additions & 1 deletion prettyqt/core/mimedatabase.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ def get_mime_type_for_data(
return core.MimeType(self.mimeTypeForData(data))

def get_mime_type_for_filename_and_data(
self, filename: os.PathLike, data: datatypes.ByteArrayType | core.QIODevice
self,
filename: str | os.PathLike[str],
data: datatypes.ByteArrayType | core.QIODevice,
) -> core.MimeType:
path = os.fspath(filename)
return core.MimeType(self.mimeTypeForFileNameAndData(path, data))
Expand Down
16 changes: 11 additions & 5 deletions prettyqt/custom_widgets/crossfadewidget.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
class CrossFadeWidget(widgets.Widget):
def __init__(
self,
pixmap_1: gui.QPixmap | os.PathLike | None = None,
pixmap_2: gui.QPixmap | os.PathLike | None = None,
pixmap_1: gui.QPixmap | os.PathLike[str] | str | None = None,
pixmap_2: gui.QPixmap | os.PathLike[str] | str | None = None,
**kwargs,
):
super().__init__(**kwargs)
Expand All @@ -27,18 +27,24 @@ def start_fade(self, duration: int = 500):
self.timeline.start()
# self.show()

def set_pixmap_1(self, pixmap: gui.QPixmap | os.PathLike | widgets.QWidget | None):
def set_pixmap_1(
self, pixmap: gui.QPixmap | os.PathLike[str] | str | widgets.QWidget | None
):
self.pixmap_1 = self._get_pixmap(pixmap)
self.updateGeometry()
self.repaint()

def set_pixmap_2(self, pixmap: gui.QPixmap | os.PathLike | widgets.QWidget | None):
def set_pixmap_2(
self, pixmap: gui.QPixmap | os.PathLike[str] | str | widgets.QWidget | None
):
self.pixmap_2 = self._get_pixmap(pixmap)
self.updateGeometry()
self.repaint()

@staticmethod
def _get_pixmap(pixmap: gui.QPixmap | os.PathLike | widgets.QWidget | None):
def _get_pixmap(
pixmap: gui.QPixmap | os.PathLike[str] | str | widgets.QWidget | None,
):
match pixmap:
case gui.QPixmap():
return pixmap
Expand Down
6 changes: 3 additions & 3 deletions prettyqt/custom_widgets/imageviewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def draw_size(p: gui.Painter, rect: core.Rect, w: int, h: int):
f = p.font()
f.setBold(True)
p.setFont(f)
sz = "\u00a0%d x %d\u00a0" % (w, h)
sz = f"\u00a0{w:d} x {h:d}\u00a0"
flags = (
constants.AlignmentFlag.AlignBottom
| constants.AlignmentFlag.AlignRight
Expand All @@ -55,7 +55,7 @@ def draw_size(p: gui.Painter, rect: core.Rect, w: int, h: int):
class ImageViewer(widgets.Widget):
def __init__(
self,
image: gui.QPixmap | os.PathLike | None = None,
image: gui.QPixmap | os.PathLike[str] | str | None = None,
*,
show_border: bool = True,
show_size: bool = False,
Expand All @@ -70,7 +70,7 @@ def __init__(
self.draw_border = show_border
self.show_size = show_size

def set_image(self, pixmap: gui.QPixmap | os.PathLike | None):
def set_image(self, pixmap: gui.QPixmap | os.PathLike[str] | str | None):
match pixmap:
case gui.QPixmap():
self._pixmap = pixmap
Expand Down
2 changes: 1 addition & 1 deletion prettyqt/custom_widgets/itemviews/filetree.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def _on_current_changed(self, new, _):
path = new.data(model.Roles.FilePathRole)
self.tool_bar.set_breadcrumbs(path)

def _update_root(self, path: os.PathLike):
def _update_root(self, path: os.PathLike[str]):
if pathlib.Path(path).exists():
self._file_tree.setRoot(os.fspath(path))

Expand Down
2 changes: 1 addition & 1 deletion prettyqt/custom_widgets/numfilterwidget.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def _on_menu_click(self, action: gui.QAction):

def get_filter_fn(self) -> Callable:
val = self.lineedit.get_value()
if val == "":
if not val:
return lambda x: True
val = float(val)
match self.op_button.text():
Expand Down
4 changes: 2 additions & 2 deletions prettyqt/gui/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def from_pil(cls, image) -> Self:
return img

@classmethod
def for_mimetype(cls, path: os.PathLike) -> Self | None:
def for_mimetype(cls, path: os.PathLike[str] | str) -> Self | None:
"""Try to create an icon from theme using the file mimetype.
E.g.::
Expand All @@ -171,7 +171,7 @@ def for_mimetype(cls, path: os.PathLike) -> Self | None:
icon = cls(cls.fromTheme(icon))
if not icon.isNull():
return icon
return None # gui.Icon.fromTheme("text-x-generic")
return None # gui.Icon.fromTheme("text-x-generic")

def to_pil(self):
from PIL import Image as PILImage
Expand Down
5 changes: 4 additions & 1 deletion prettyqt/gui/pixmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,10 @@ def from_image(
return cls(cls.fromImage(img, flag))

def save_to_file(
self, path: os.PathLike, fmt: str = "png", quality: int | None = None
self,
path: str | os.PathLike[str],
fmt: str = "png",
quality: int | None = None,
) -> bool:
return self.save(os.fspath(path), fmt, -1 if quality is None else quality)

Expand Down
2 changes: 1 addition & 1 deletion prettyqt/gui/window.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def set_modality(
def get_modality(self) -> constants.WindowModalityStr:
return constants.WINDOW_MODALITY.inverse[self.modality()]

def set_file_path(self, file_path: os.PathLike):
def set_file_path(self, file_path: str | os.PathLike[str]):
path = os.fspath(file_path)
self.setFilePath(path)

Expand Down
2 changes: 1 addition & 1 deletion prettyqt/ipython/outofprocessipythonwidget.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
# asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())


def run_server(connection_file: os.PathLike):
def run_server(connection_file: str | os.PathLike[str]):
IPython.embed_kernel(
local_ns=sys._getframe(1).f_locals,
connection_file=os.fspath(connection_file),
Expand Down
2 changes: 1 addition & 1 deletion prettyqt/itemmodels/fsspecmodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ def rmdir(self, index: core.QModelIndex | str) -> bool:
self.fs.rmdir(path)
return self.fs.exists(path)

def setRootPath(self, path: os.PathLike | None) -> core.ModelIndex:
def setRootPath(self, path: str | os.PathLike[str] | None) -> core.ModelIndex:
path = os.fspath(path) if path else self.fs.root_marker
item = self.fs.info(path)
self.set_root_item(item)
Expand Down
6 changes: 4 additions & 2 deletions prettyqt/itemmodels/gitpythontreemodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class GitPythonTreeModel(itemmodels.TreeModel):
# "Executable mode",
]

def __init__(self, path: os.PathLike | str | git.Tree | git.Repo, **kwargs):
def __init__(self, path: os.PathLike[str] | str | git.Tree | git.Repo, **kwargs):
match path:
case os.PathLike() | str():
tree = git.Repo(path).tree()
Expand Down Expand Up @@ -151,7 +151,9 @@ class GitPythonCommitTreeModel(itemmodels.TreeModel):
]

def __init__(
self, repo: os.PathLike | str | git.Tree | git.Repo | git.Commit, **kwargs
self,
repo: os.PathLike[str] | str | git.Tree | git.Repo | git.Commit,
**kwargs,
):
match repo:
case os.PathLike() | str():
Expand Down
2 changes: 1 addition & 1 deletion prettyqt/itemmodels/moduleinfomodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class ModuleInfoModel(itemmodels.TreeModel):
"""Tree Model to display a module hierarchy (using pkgutil)."""

HEADER = ["Name", "Path", "Is Package"]
SUPPORTS = str | os.PathLike | types.ModuleType | pkgutil.ModuleInfo
SUPPORTS = str | os.PathLike[str] | types.ModuleType | pkgutil.ModuleInfo

def __init__(self, obj, **kwargs):
match obj:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,7 @@ def data(
and (
(self._mode == "column" and index.column() == self._current_column)
or (
self._mode == "row"
and (index.row() == self._current_row)
(self._mode == "row" and (index.row() == self._current_row))
or self._mode == "all"
)
)
Expand Down
4 changes: 3 additions & 1 deletion prettyqt/multimedia/mediarecorder.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@


class MediaRecorder(core.ObjectMixin, QtMultimedia.QMediaRecorder):
def set_output_location(self, url: datatypes.UrlType | os.PathLike | None = None):
def set_output_location(
self, url: datatypes.UrlType | os.PathLike[str] | None = None
):
url = datatypes.to_local_url(url)
self.setOutputLocation(url)

Expand Down
2 changes: 1 addition & 1 deletion prettyqt/qml/qmlapplicationengine.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def __iter__(self) -> Iterator[QtCore.QObject]:
def load_data(
self,
data: datatypes.ByteArrayType,
url: datatypes.UrlType | os.PathLike | None = None,
url: datatypes.UrlType | os.PathLike[str] | None = None,
):
data = datatypes.to_bytearray(data)
url = datatypes.to_local_url(url)
Expand Down
2 changes: 1 addition & 1 deletion prettyqt/syntaxhighlighters/regexmatchhighlighter.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def highlightBlock(self, text: str):
break
starts_in_line = start_char <= start <= end_char
ends_in_line = start_char <= end <= end_char
if starts_in_line and ends_in_line or not ends_in_line and starts_in_line:
if (starts_in_line and ends_in_line) or (not ends_in_line and starts_in_line):
# print(f"in line: {line_pos} - {line_pos + match_len}")
self._colorize(start - start_char, end - start, i)
elif ends_in_line:
Expand Down
8 changes: 4 additions & 4 deletions prettyqt/utils/classhelpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def to_module(
except (ImportError, AttributeError) as e:
logger.warning(f"Could not import {module_path!r}")
if return_none:
return
return None
raise e
case types.ModuleType():
return module
Expand Down Expand Up @@ -93,7 +93,7 @@ def to_module_parts(module: Sequence[str] | str | types.ModuleType) -> tuple[str

def find_common_ancestor(cls_list: list[type]) -> type:
mros = [list(inspect.getmro(cls)) for cls in cls_list]
track = collections.defaultdict(int)
track: collections.defaultdict[type, int] = collections.defaultdict(int)
while mros:
for mro in mros:
cur = mro.pop(0)
Expand All @@ -105,7 +105,7 @@ def find_common_ancestor(cls_list: list[type]) -> type:
):
return cur
if len(mro) == 0:
mros.remove(mro)
mros.remove(mro) # noqa: B909
raise TypeError("Couldnt find common base class")


Expand Down Expand Up @@ -202,7 +202,7 @@ def iter_classes_for_module(
"""
module = to_module(module)
if not module:
return []
return
if recursive:
for _name, submod in inspect.getmembers(module, inspect.ismodule):
if submod.__name__.startswith(module_filter or ""):
Expand Down
4 changes: 2 additions & 2 deletions prettyqt/utils/datatypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def __call__(cls, *args, **kw):
PatternType = re.Pattern | QtCore.QRegularExpression
PatternAndStringType = str | PatternType
JSONType = str | int | float | bool | None | dict[str, Any] | list[Any]
PathType = str | os.PathLike
PathType = str | os.PathLike[str]


class Validatable(Protocol):
Expand Down Expand Up @@ -589,7 +589,7 @@ def to_url(url: UrlType | None) -> QtCore.QUrl:
raise TypeError(url)


def to_local_url(url: UrlType | os.PathLike | None) -> QtCore.QUrl:
def to_local_url(url: UrlType | os.PathLike[str] | None) -> QtCore.QUrl:
# TODO: need to check whether we should merge to_local_url and to_url
# core.Url.from_user_input() perhaps a good option, too?
match url:
Expand Down
Loading

0 comments on commit 1568d7d

Please sign in to comment.