Skip to content

Commit bcd88cb

Browse files
committed
More fixes from flake8 and mypy
1 parent debae78 commit bcd88cb

15 files changed

+88
-63
lines changed

pygame_gui/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
from pygame_gui._constants import TEXT_EFFECT_SHAKE
4949
from pygame_gui._constants import TEXT_EFFECT_EXPAND_CONTRACT
5050
from pygame_gui._constants import UITextEffectType
51-
from pygame_gui.core.utility import PackageResource
51+
from pygame_gui.core.package_resource import PackageResource
5252

5353
__all__ = [
5454
"UIManager",

pygame_gui/core/colour_parser.py

+11-7
Original file line numberDiff line numberDiff line change
@@ -218,9 +218,11 @@ class ColourValueParserData(TypedDict):
218218
},
219219
NumParserType.INT: {"validator": is_int_str, "parser": int},
220220
}
221-
"""A mapping for each NumParserType to its corresponding validator and parser for strings of that type's
222-
specification"""
223221

222+
"""
223+
A mapping for each NumParserType to its corresponding validator and parser for strings of that type's
224+
specification
225+
"""
224226
_colourModelSchemas: Dict[str, List[NumParserType]] = {
225227
"hsl": [NumParserType.DEGREE, NumParserType.PERCENTAGE, NumParserType.PERCENTAGE],
226228
"hsla": [
@@ -659,11 +661,13 @@ def parse_colour_name(strdata: str) -> pygame.Color:
659661
(is_valid_hsv_string, parse_hsv_string),
660662
(is_valid_hsva_string, parse_hsva_string),
661663
]
662-
"""The list of validator and parser function pairs that will be used by is_valid_colour_string and
663-
parse_colour_string The functions have no requirement other than the validator confirming a schema and the parser
664-
returning a pygame.Color value from the string data if it is valid Note that if new validator and parsing formulas
665-
are added, these validators should not overlap if it can be helped, as there's no way to determine whether one colour
666-
could be more "valid" than another in that case"""
664+
"""
665+
The list of validator and parser function pairs that will be used by is_valid_colour_string and
666+
parse_colour_string The functions have no requirement other than the validator confirming a schema and the parser
667+
returning a pygame.Color value from the string data if it is valid Note that if new validator and parsing formulas
668+
are added, these validators should not overlap if it can be helped, as there's no way to determine whether one colour
669+
could be more "valid" than another in that case
670+
"""
667671

668672

669673
def is_valid_colour_string(strdata: str) -> bool:

pygame_gui/core/gui_font_pygame.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Union, IO, Optional, Dict, Tuple
1+
from typing import Union, IO, Optional, Dict, Tuple, Any
22
from os import PathLike
33

44
import pygame
@@ -31,13 +31,13 @@ def __init__(
3131
file: Optional[FileArg],
3232
size: Union[int, float],
3333
force_style: bool = False,
34-
style: Optional[Dict[str, bool]] = None,
34+
style: Optional[Dict[str, Any]] = None,
3535
):
3636
self.__internal_font: Font = Font(
37-
file, size
37+
file, int(size)
3838
) # no resolution option for pygame font?
3939

40-
self.__internal_font.set_point_size(size)
40+
self.__internal_font.set_point_size(int(size))
4141
self.pad = True
4242
self.origin = True
4343
self.__underline = False # pylint: disable=unused-private-member

pygame_gui/core/interfaces/appearance_theme_interface.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
IColourGradientInterface,
1515
)
1616
from pygame_gui.core.interfaces.gui_font_interface import IGUIFontInterface
17+
from pygame_gui.core.package_resource import PackageResource
1718

1819

1920
class IUIAppearanceThemeInterface(metaclass=ABCMeta):
@@ -161,7 +162,7 @@ def get_colour_or_gradient(
161162

162163
@abstractmethod
163164
def load_theme(
164-
self, file_path: Union[str, PathLike, io.StringIO, "PackageResource", dict]
165+
self, file_path: Union[str, PathLike, io.StringIO, PackageResource, dict]
165166
):
166167
"""
167168
Loads a theme, and currently, all associated data like fonts and images required

pygame_gui/core/interfaces/gui_font_interface.py

+3
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ class IGUIFontInterface(metaclass=ABCMeta):
88
A font interface, so we can easily switch between pygame.freetype.Font and pygame.Font.
99
"""
1010

11+
@abstractmethod
1112
def size(self, text: str) -> Tuple[int, int]:
1213
"""
1314
Return the pixel size of a given text string in this font
@@ -23,6 +24,7 @@ def render_premul(self, text: str, text_color: Color) -> Surface:
2324
Draws text to a surface ready for pre-multiplied alpha-blending
2425
"""
2526

27+
@abstractmethod
2628
def render_premul_to(
2729
self,
2830
text: str,
@@ -102,6 +104,7 @@ def underline_adjustment(self, value: float):
102104
:return:
103105
"""
104106

107+
@abstractmethod
105108
def get_direction(self) -> int:
106109
"""
107110

pygame_gui/core/object_id.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from collections import namedtuple
22

33
ObjectID = namedtuple(
4-
"ObjectID", field_names=("object_id", "class_id"), defaults=(None, None)
4+
"ObjectID", ("object_id", "class_id"), defaults=(None, None)
55
)

pygame_gui/core/package_resource.py

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import os
2+
import sys
3+
from typing import Union
4+
from pathlib import Path
5+
6+
7+
def _create_resource_path(relative_path: Union[str, Path]):
8+
"""
9+
Get absolute path to resource, works for dev and for PyInstaller's 'onefile' mode
10+
11+
:param relative_path: A relative path to a file of some kind.
12+
13+
"""
14+
15+
try:
16+
# PyInstaller creates a temp folder and stores path in _MEIPASS
17+
if getattr(sys, 'frozen', False):
18+
base_path = sys._MEIPASS # type: ignore # pylint: disable=no-member,protected-access
19+
else:
20+
base_path = os.path.abspath(".")
21+
except AttributeError:
22+
base_path = os.path.abspath(".")
23+
24+
return os.path.join(base_path, relative_path)
25+
26+
27+
class PackageResource:
28+
"""
29+
A data class to handle input for importlib.resources as single parameter.
30+
31+
:param package: The python package our resource is located in (e.g. 'pygame_gui.data')
32+
:param resource: The name of the resource (e.g. 'default_theme.json')
33+
"""
34+
35+
def __init__(self, package: str, resource: str):
36+
self.package = package
37+
self.resource = resource
38+
39+
def __repr__(self):
40+
return f"{self.package}.{self.resource}"
41+
42+
def to_path(self) -> str:
43+
"""
44+
If we don't have any importlib module to use, we can try to turn the resource into a file
45+
path.
46+
47+
:return: A string path.
48+
"""
49+
root_path = ""
50+
relative_path = self.package.replace(".", "/") + "/" + self.resource
51+
if self.package.find("pygame_gui") == 0:
52+
# This is default data from pygame_gui so relative to pygame_gui rather than app
53+
root_path = os.path.abspath(
54+
os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
55+
)
56+
return _create_resource_path(os.path.join(root_path, relative_path))

pygame_gui/core/ui_appearance_theme.py

+3-11
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import warnings
55

66
from contextlib import contextmanager
7+
from importlib.resources import files, as_file
78
from typing import Union, List, Dict, Any, Optional
89

910
import pygame
@@ -18,8 +19,9 @@
1819
from pygame_gui.core.interfaces.appearance_theme_interface import (
1920
IUIAppearanceThemeInterface,
2021
)
21-
from pygame_gui.core.utility import create_resource_path, PackageResource
22+
from pygame_gui.core.utility import create_resource_path
2223
from pygame_gui.core.utility import ImageResource, SurfaceResource
24+
from pygame_gui.core.package_resource import PackageResource
2325
from pygame_gui.core.ui_font_dictionary import UIFontDictionary
2426
from pygame_gui.core.ui_shadow import ShadowGenerator
2527
from pygame_gui.core.surface_cache import SurfaceCache
@@ -30,16 +32,6 @@
3032
get_commas_outside_enclosing_glyphs,
3133
)
3234

33-
# First try importlib
34-
# Then importlib_resources
35-
try:
36-
from importlib.resources import files, as_file
37-
except ImportError:
38-
try:
39-
from importlib_resources import files, as_file
40-
except ImportError as no_import_lib:
41-
raise ImportError from no_import_lib
42-
4335

4436
class UIAppearanceTheme(IUIAppearanceThemeInterface):
4537
"""

pygame_gui/core/ui_font_dictionary.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
IUIFontDictionaryInterface,
1111
)
1212
from pygame_gui.core.resource_loaders import IResourceLoader
13-
from pygame_gui.core.utility import PackageResource
13+
from pygame_gui.core.package_resource import PackageResource
1414
from pygame_gui.core.utility import FontResource
1515

1616

pygame_gui/core/ui_shadow.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@ def find_closest_shadow_scale_to_size(
360360
"""
361361
lowest_diff = 1000000000000
362362
closest_key = None
363-
if shape == "rectangle":
363+
if shape == "rectangle" and corner_radius is not None:
364364
return self.create_new_rectangle_shadow(
365365
size[0], size[1], shadow_width, corner_radius
366366
)

pygame_gui/core/utility.py

+1-33
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
from pygame_gui.core.interfaces import IUIManagerInterface, IGUIFontInterface
2727
from pygame_gui.core.gui_font_freetype import GUIFontFreetype
2828
from pygame_gui.core.gui_font_pygame import GUIFontPygame
29-
29+
from pygame_gui.core.package_resource import PackageResource
3030

3131
__default_manager: Optional[IUIManagerInterface] = None # pylint: disable=invalid-name
3232

@@ -365,38 +365,6 @@ def apply_colour_to_surface(
365365
shape_surface.blit(colour_surface, (0, 0), special_flags=pygame.BLEND_RGBA_MULT)
366366

367367

368-
class PackageResource:
369-
"""
370-
A data class to handle input for importlib.resources as single parameter.
371-
372-
:param package: The python package our resource is located in (e.g. 'pygame_gui.data')
373-
:param resource: The name of the resource (e.g. 'default_theme.json')
374-
"""
375-
376-
def __init__(self, package: str, resource: str):
377-
self.package = package
378-
self.resource = resource
379-
380-
def __repr__(self):
381-
return f"{self.package}.{self.resource}"
382-
383-
def to_path(self) -> str:
384-
"""
385-
If we don't have any importlib module to use, we can try to turn the resource into a file
386-
path.
387-
388-
:return: A string path.
389-
"""
390-
root_path = ""
391-
relative_path = self.package.replace(".", "/") + "/" + self.resource
392-
if self.package.find("pygame_gui") == 0:
393-
# This is default data from pygame_gui so relative to pygame_gui rather than app
394-
root_path = os.path.abspath(
395-
os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
396-
)
397-
return create_resource_path(os.path.join(root_path, relative_path))
398-
399-
400368
class FontResource:
401369
"""
402370
A resource class to handle all the data we need to load a python font object from a

pygame_gui/elements/ui_text_box.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ def __init__(
168168

169169
self.link_hover_chunks = [] # container for any link chunks we have
170170

171-
self.active_text_effect = None # type: Optional[TextEffect]
171+
self.active_text_effect: Optional[TextEffect] = None
172172
self.active_text_chunk_effects = []
173173

174174
self.scroll_bar_width = 20

pygame_gui/ui_manager.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@
2222
BlockingThreadedResourceLoader,
2323
)
2424
from pygame_gui.core.utility import (
25-
PackageResource,
2625
get_default_manager,
2726
set_default_manager,
2827
)
28+
from pygame_gui.core.package_resource import PackageResource
2929
from pygame_gui.core.layered_gui_group import LayeredGUIGroup
3030
from pygame_gui.core import ObjectID
3131

pygame_gui/windows/ui_file_dialog.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def __init__(
115115

116116
self.last_valid_directory_path = self.current_directory_path
117117

118-
self.current_file_list = None # type: Union[List[str], None]
118+
self.current_file_list: Optional[List[str]] = None
119119
self.update_current_file_list()
120120

121121
self._setup_ui_elements()

setup.cfg

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
description_file = README.md
44
[flake8]
55
max-line-length = 120
6+
extend-ignore = E203
67
[pylint.MESSAGES CONTROL]
78
extension-pkg-whitelist=pygame
89
disable=no-else-return,too-many-instance-attributes,too-many-ancestors,too-many-return-statements,too-many-boolean-expressions,too-many-branches,too-many-arguments,too-many-statements,too-many-locals,too-many-lines,too-many-positional-arguments,too-many-public-methods,too-many-nested-blocks,missing-module-docstring,too-few-public-methods,fixme,duplicate-code

0 commit comments

Comments
 (0)