Skip to content

Commit 833005a

Browse files
chore: improve typing (#417)
1 parent 7094347 commit 833005a

7 files changed

Lines changed: 95 additions & 62 deletions

File tree

apps/perspectivator/perspectivator.wand.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@
2626
from dataclasses import dataclass
2727
from typing import Optional,Tuple,List,Dict
2828

29+
from PIL import ImageDraw, ImageFilter
30+
2931
import numpy as np
3032

3133
from wand.image import Image

libs/pyTermTk/TermTk/TTkCore/constant.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222

2323
__all__ = ['TTkConstant', 'TTkK']
2424

25+
from enum import IntEnum
26+
2527
class TTkConstant:
2628
'''Class container of all the constants used in :mod:`~TermTk`'''
2729

@@ -56,7 +58,7 @@ class ColorType(int):
5658
ColorModifier = 0x08
5759
'''The :py:class:`TTkColor` include a color modifier based on :py:class:`TTkColorModifier`'''
5860

59-
class FocusPolicy(int):
61+
class FocusPolicy(IntEnum):
6062
'''
6163
This Class type defines the various policies a widget
6264
can have with respect to acquiring keyboard focus.

libs/pyTermTk/TermTk/TTkCore/string.py

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,15 @@
2020
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2121
# SOFTWARE.
2222

23+
from __future__ import annotations
24+
2325
__all__ = ['TTkString']
2426

2527
import os
2628
import re
2729
import unicodedata
2830
from types import GeneratorType
29-
from typing import Any
30-
31-
try:
32-
from typing import Self
33-
except:
34-
class Self(): pass
31+
from typing import Any, Optional, Union, List, Tuple
3532

3633
from TermTk.TTkCore.cfg import TTkCfg
3734
from TermTk.TTkCore.constant import TTkK
@@ -69,11 +66,13 @@ class TTkString():
6966
unicodeWideOverflowColor = TTkColor.fg("#888888")+TTkColor.bg("#000088")
7067

7168
__slots__ = ('_text','_colors','_baseColor','_hasTab','_hasSpecialWidth')
72-
69+
_text:str
70+
_colors:List[TTkColor]
71+
_baseColor:TTkColor
7372
def __init__(self,
74-
text:str="",
75-
color:TTkColor=None) -> None:
76-
if issubclass(type(text), TTkString):
73+
text:Union[str,TTkString]="",
74+
color:Optional[TTkColor]=None) -> None:
75+
if isinstance(text, TTkString):
7776
self._text = text._text
7877
self._colors = text._colors if color is None else [color]*len(self._text)
7978
self._baseColor = text._baseColor
@@ -120,7 +119,7 @@ def __len__(self) -> int:
120119
def __str__(self) -> str:
121120
return self._text
122121

123-
def __add__(self, other:Self) -> Self:
122+
def __add__(self, other:TTkString) -> TTkString:
124123
ret = TTkString()
125124
ret._baseColor = self._baseColor
126125
if isinstance(other, TTkString):
@@ -142,7 +141,7 @@ def __add__(self, other:Self) -> Self:
142141
ret._baseColor = other
143142
return ret
144143

145-
def __radd__(self, other:Self) -> Self:
144+
def __radd__(self, other:TTkString) -> TTkString:
146145
ret = TTkString()
147146
ret._baseColor = self._baseColor
148147
if isinstance(other, TTkString):
@@ -180,7 +179,7 @@ def __ne__(self, other): return self._text != other._text if issubclass(type(oth
180179
def __gt__(self, other): return self._text > other._text if issubclass(type(other),TTkString) else self._text > other
181180
def __ge__(self, other): return self._text >= other._text if issubclass(type(other),TTkString) else self._text >= other
182181

183-
def sameAs(self, other:Self) -> bool:
182+
def sameAs(self, other:TTkString) -> bool:
184183
if not issubclass(type(other),TTkString): return False
185184
return (
186185
self==other and
@@ -190,7 +189,7 @@ def sameAs(self, other:Self) -> bool:
190189
def isdigit(self) -> bool:
191190
return self._text.isdigit()
192191

193-
def lstrip(self, ch:str) -> Self:
192+
def lstrip(self, ch:str) -> TTkString:
194193
ret = TTkString()
195194
ret._text = self._text.lstrip(ch)
196195
ret._colors = self._colors[-len(ret._text):]
@@ -199,7 +198,7 @@ def lstrip(self, ch:str) -> Self:
199198
def charAt(self, pos:int) -> str:
200199
return self._text[pos]
201200

202-
def setCharAt(self, pos:int, char:str) -> Self:
201+
def setCharAt(self, pos:int, char:str) -> TTkString:
203202
self._text = self._text[:pos]+char+self._text[pos+1:]
204203
self._checkWidth()
205204
return self
@@ -209,11 +208,11 @@ def colorAt(self, pos:int) -> TTkColor:
209208
return TTkColor()
210209
return self._colors[pos]
211210

212-
def setColorAt(self, pos, color) -> Self:
211+
def setColorAt(self, pos, color) -> TTkString:
213212
self._colors[pos] = color
214213
return self
215214

216-
def tab2spaces(self, tabSpaces=4) -> Self:
215+
def tab2spaces(self, tabSpaces=4) -> TTkString:
217216
'''Return the string representation with the tabs (converted in spaces) trimmed and aligned'''
218217
if not self._hasTab: return self
219218
ret = TTkString()
@@ -327,7 +326,7 @@ def toAnsi(self, strip=False):
327326
return out
328327
return out+str(TTkColor.RST)
329328

330-
def align(self, width=None, color=TTkColor.RST, alignment=TTkK.NONE) -> Self:
329+
def align(self, width=None, color=TTkColor.RST, alignment=TTkK.NONE) -> TTkString:
331330
''' Align the string
332331
333332
:param width: the new width
@@ -389,7 +388,7 @@ def align(self, width=None, color=TTkColor.RST, alignment=TTkK.NONE) -> Self:
389388

390389
return ret
391390

392-
def extractShortcuts(self) -> Self:
391+
def extractShortcuts(self) -> Tuple[TTkString,List[str]]:
393392
def _chGenerator():
394393
for ch,color in zip(self._text,self._colors):
395394
yield ch,color
@@ -406,7 +405,7 @@ def _chGenerator():
406405
_newColors.append(color)
407406
return TTkString._importString1(_newText,_newColors), _ret
408407

409-
def replace(self, *args, **kwargs) -> Self:
408+
def replace(self, *args, **kwargs) -> TTkString:
410409
''' **replace** (*old*, *new*, *count*)
411410
412411
Replace "**old**" match with "**new**" string for "**count**" times
@@ -454,7 +453,7 @@ def replace(self, *args, **kwargs) -> Self:
454453

455454
return ret
456455

457-
def completeColor(self, color:TTkColor, match=None, posFrom=None, posTo=None) -> Self:
456+
def completeColor(self, color:TTkColor, match=None, posFrom=None, posTo=None) -> TTkString:
458457
''' Complete the color of the entire string or a slice of it
459458
460459
The Fg and/or Bg of the string is replaced with the selected Fg/Bg color only if missing
@@ -495,7 +494,7 @@ def completeColor(self, color:TTkColor, match=None, posFrom=None, posTo=None) ->
495494
return ret
496495

497496

498-
def setColor(self, color, match=None, posFrom=None, posTo=None) -> Self:
497+
def setColor(self, color, match=None, posFrom=None, posTo=None) -> TTkString:
499498
''' Set the color of the entire string or a slice of it
500499
501500
If only the color is specified, the entire string is colorized
@@ -531,7 +530,7 @@ def setColor(self, color, match=None, posFrom=None, posTo=None) -> Self:
531530
ret._colors += self._colors
532531
return ret
533532

534-
def substring(self, fr=None, to=None) -> Self:
533+
def substring(self, fr=None, to=None) -> TTkString:
535534
''' Return the substring
536535
537536
:param fr: the starting of the slice, defaults to 0
@@ -546,7 +545,7 @@ def substring(self, fr=None, to=None) -> Self:
546545
ret._fastCheckWidth(self._hasSpecialWidth)
547546
return ret
548547

549-
def split(self, separator ) -> list[Self]:
548+
def split(self, separator ) -> list[TTkString]:
550549
''' Split the string using a separator
551550
552551
.. note:: Only a one char separator is currently supported
@@ -599,7 +598,7 @@ def findall(self, regexp, ignoreCase=False):
599598
def getIndexes(self, char):
600599
return [i for i,c in enumerate(self._text) if c==char]
601600

602-
def join(self, strings:list[Self]) -> Self:
601+
def join(self, strings:list[TTkString]) -> TTkString:
603602
''' Join the input strings using the current as separator
604603
605604
:param strings: the list of strings to be joined

libs/pyTermTk/TermTk/TTkWidgets/container.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222

2323
__all__ = ['TTkContainer', 'TTkPadding']
2424

25-
from typing import NamedTuple
25+
from typing import NamedTuple, Optional
2626

2727
from TermTk.TTkCore.constant import TTkK
2828
from TermTk.TTkCore.log import TTkLog
@@ -104,8 +104,8 @@ class TTkContainer(TTkWidget):
104104
'_layout')
105105

106106
def __init__(self, *,
107-
layout:TTkLayout=None,
108-
padding:TTkPadding = None,
107+
layout:Optional[TTkLayout]=None,
108+
padding:Optional[TTkPadding] = None,
109109
paddingTop:int = 0,
110110
paddingBottom:int = 0,
111111
paddingLeft:int = 0,
@@ -381,7 +381,7 @@ def update(self, repaint: bool = True, updateLayout: bool = False, updateParent:
381381
self._height - self._padt - self._padb)
382382
self.rootLayout().update()
383383

384-
def getWidgetByName(self, name: str) -> TTkWidget:
384+
def getWidgetByName(self, name: str) -> Optional[TTkWidget]:
385385
'''
386386
Return the widget from its name.
387387

libs/pyTermTk/TermTk/TTkWidgets/widget.py

Lines changed: 57 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,11 @@
2020
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2121
# SOFTWARE.
2222

23-
__all__ = ['TTkWidget']
23+
from __future__ import annotations
2424

25-
from typing import Callable, Any, List
25+
__all__ = ['TTkWidget']
2626

27-
try:
28-
from typing import Self
29-
except:
30-
class Self(): pass
27+
from typing import ( TYPE_CHECKING, Callable, Any, List, Optional, Tuple, Union, Dict )
3128

3229
from TermTk.TTkCore.cfg import TTkCfg, TTkGlbl
3330
from TermTk.TTkCore.constant import TTkK
@@ -43,6 +40,9 @@ class Self(): pass
4340
from TermTk.TTkLayouts.layout import TTkWidgetItem
4441
from TermTk.TTkCore.TTkTerm.inputmouse import TTkMouseEvent
4542

43+
if TYPE_CHECKING:
44+
from TermTk import TTkContainer
45+
4646
class TTkWidget(TMouseEvents,TKeyEvents, TDragEvents):
4747
''' Widget sizes:
4848
@@ -122,25 +122,51 @@ class TTkWidget(TMouseEvents,TKeyEvents, TDragEvents):
122122
#Signals
123123
'focusChanged', 'sizeChanged', 'currentStyleChanged', 'closed')
124124

125-
def __init__(self,
126-
parent:Self = None,
127-
x:int=0, y:int=0,
128-
width:int=0, height:int=0,
129-
pos : tuple = None,
130-
size : tuple = None,
131-
maxSize : tuple = None,
132-
maxWidth : int = 0x10000,
133-
maxHeight: int = 0x10000,
134-
minSize : tuple = None,
135-
minWidth : int = 0x00000,
136-
minHeight: int = 0x00000,
137-
name : str = None,
138-
visible : bool = True,
139-
enabled : bool = True,
140-
toolTip : TTkString = '',
141-
style : dict = None,
142-
addStyle : dict = None,
143-
**kwargs) -> None:
125+
_name:str
126+
_parent:Optional[TTkContainer]
127+
_x:int
128+
_y:int
129+
_width:int
130+
_height:int
131+
_maxw:int
132+
_maxh:int
133+
_minw:int
134+
_minh:int
135+
_focus:bool
136+
_focus_policy:TTkK.FocusPolicy
137+
_canvas:TTkCanvas
138+
_widgetItem:TTkWidgetItem
139+
_visible:bool
140+
_pendingMouseRelease:bool
141+
_enabled:bool
142+
_style:Dict
143+
_currentStyle:Dict
144+
_toolTip:TTkString
145+
_dropEventProxy:Any
146+
_widgetCursor:Tuple[int,int]
147+
_widgetCursorEnabled:bool
148+
_widgetCursorType:int
149+
150+
def __init__(
151+
self,
152+
parent:Optional[TTkContainer] = None,
153+
x:int=0, y:int=0,
154+
width:int=0, height:int=0,
155+
pos : Optional[Tuple[int,int]] = None,
156+
size : Optional[Tuple[int,int]] = None,
157+
maxSize : Optional[Tuple[int,int]] = None,
158+
maxWidth : int = 0x10000,
159+
maxHeight: int = 0x10000,
160+
minSize : Optional[Tuple[int,int]] = None,
161+
minWidth : int = 0x00000,
162+
minHeight: int = 0x00000,
163+
name : Optional[str] = None,
164+
visible : bool = True,
165+
enabled : bool = True,
166+
toolTip : Union[TTkString,str] = '',
167+
style : Optional[Dict] = None,
168+
addStyle : Optional[Dict] = None,
169+
**kwargs) -> None:
144170
'''
145171
:param name: the name of the widget, defaults to ""
146172
:type name: str, optional
@@ -401,7 +427,7 @@ def pasteEvent(self, txt:str) -> None:
401427
:param txt: the paste object
402428
:type txt: str
403429
'''
404-
return False
430+
pass
405431

406432
def _mouseEventParseChildren(self, evt:TTkMouseEvent) -> bool:
407433
return False
@@ -813,14 +839,15 @@ def getWidgetByName(self, name: str):
813839
_S_PRESSED = 0x20
814840
_S_RELEASED = 0x40
815841

816-
def style(self) -> dict:
842+
def style(self) -> Dict:
817843
return self._style.copy()
818844

819-
def currentStyle(self) -> dict:
845+
def currentStyle(self) -> Dict:
820846
return self._currentStyle
821847

822-
def setCurrentStyle(self, style) -> dict:
823-
if style == self._currentStyle: return
848+
def setCurrentStyle(self, style) -> None:
849+
if style == self._currentStyle:
850+
return
824851
self._currentStyle = style
825852
self.currentStyleChanged.emit(style)
826853
self.update()

tools/check.import.sh

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ __check(){
88
grep -v -e "import re" -e "import os" -e "import datetime" |
99
grep -v \
1010
-e "from dataclasses" \
11+
-e "from __future__ import annotations" \
1112
-e "signal.py:from inspect import getfullargspec" \
1213
-e "signal.py:from types import LambdaType" \
1314
-e "signal.py:from threading import Lock" \
@@ -41,8 +42,8 @@ __check(){
4142
-e "propertyanimation.py:from types import LambdaType" \
4243
-e "propertyanimation.py:import time, math" \
4344
-e "savetools.py:import importlib.util" \
44-
-e "savetools.py:import json" |
45-
-e "TTkCore/color.py:from __future__ import annotations" |
45+
-e "savetools.py:import json" \
46+
-e "TTkCore/constant.py:from enum import IntEnum" |
4647
grep -v \
4748
-e "TTkTerm/input_mono.py:from time import time" \
4849
-e "TTkTerm/input_mono.py:import platform" \
@@ -109,6 +110,7 @@ __check(){
109110
-e "TTkTerminal/__init__.py:import importlib.util" \
110111
-e "TTkTerminal/__init__.py:import platform" |
111112
grep -v \
113+
-e "TTkWidgets/widget.py:from __future__ import annotations" \
112114
-e "TTkWidgets/tabwidget.py:from enum import Enum" \
113115
-e "TTkModelView/__init__.py:from importlib.util import find_spec" \
114116
-e "TTkModelView/tablemodelcsv.py:import csv" \

tools/image/example.projection.2.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import math
2+
import numpy as np,array
23

34
def project_3d_to_2d(square_3d, observer, look_at, fov=90, aspect_ratio=1, near=0.1, far=1000):
45
"""

0 commit comments

Comments
 (0)