Skip to content

Commit

Permalink
Several small fixes to code (#1308)
Browse files Browse the repository at this point in the history
* converted strings to f-strings

Several files had old-fashioned strings / format strings. Updated to use f-strings.

* added Exception to bare excepts

Mainly just reduces pylint noise

* corrected singleton comparisons and simplified conditional

evt == none becomes evt is None for singleton comparisons
True if x else False can just be if x

* f-strings without interpolated values

Redundant f-string specification removed

* more redundant f-strings

* replaced exit() with sys.exit()

Just exit() is best saved for repl

* R0402 - don't import as when you can do from import

Rejigged two imports to be from imports
  • Loading branch information
marksmayo authored Apr 19, 2023
1 parent 981b7b0 commit 1725a16
Show file tree
Hide file tree
Showing 27 changed files with 79 additions and 80 deletions.
10 changes: 5 additions & 5 deletions sdk/python/packages/flet-core/src/flet_core/callable_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ def _call_method(self, name: str, params: List[str], wait_for_result=True) -> An
f"Timeout waiting for {self.__class__.__name__}.{name}({params}) method call"
)
result, err = self.__results.pop(evt)
if err != None:
if err is not None:
raise Exception(err)
if result == None:
if result is None:
return None
return json.loads(result)

Expand Down Expand Up @@ -96,17 +96,17 @@ async def _call_method_async(
)

result, err = self.__results.pop(evt)
if err != None:
if err is not None:
raise Exception(err)
if result == None:
if result is None:
return None
return json.loads(result)

def _on_result(self, e):
d = json.loads(e.data)
result = ControlMethodResults(**d)
evt = self.__calls.pop(result.i, None)
if evt == None:
if evt is None:
return
self.__results[evt] = (result.r, result.e)
evt.set()
4 changes: 2 additions & 2 deletions sdk/python/packages/flet-core/src/flet_core/column.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,9 +227,9 @@ def scroll(self, value: Optional[ScrollMode]):
self.__set_scroll(value)

def __set_scroll(self, value: Optional[ScrollModeString]):
if value == True:
if value is True:
value = "auto"
elif value == False:
elif value is False:
value = None
self._set_attr("scroll", value)

Expand Down
2 changes: 1 addition & 1 deletion sdk/python/packages/flet-core/src/flet_core/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@

try:
from typing import Literal
except:
except Exception:
from typing_extensions import Literal


Expand Down
2 changes: 1 addition & 1 deletion sdk/python/packages/flet-core/src/flet_core/control.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def __str__(self):
attrs = {}
for k, v in self.__attrs.items():
attrs[k] = v[0]
return "{} {}".format(self._get_control_name(), attrs)
return f"{self._get_control_name()} {attrs}"

# event_handlers
@property
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def _create_update_control_props_handler_arg(self, msg: ClientMessage):
)

def _process_command(self, command: Command):
logger.debug("_process_command: {}".format(command))
logger.debug(f"_process_command: {command}")
if command.name == "get":
return self._process_get_command(command.values)
elif command.name == "add":
Expand All @@ -89,7 +89,7 @@ def _process_command(self, command: Command):
return self._process_invoke_method_command(command.values, command.attrs)
elif command.name == "error":
return self._process_error_command(command.values)
raise Exception("Unsupported command: {}".format(command.name))
raise Exception(f"Unsupported command: {command.name}")

def _process_add_command(self, command: Command):

Expand Down Expand Up @@ -131,7 +131,7 @@ def _process_add_command(self, command: Command):

id = cmd.attrs.get("id", "")
if not id:
id = "_{}".format(self._control_id)
id = f"_{self._control_id}"
self._control_id += 1
cmd.attrs["id"] = id

Expand Down
4 changes: 2 additions & 2 deletions sdk/python/packages/flet-core/src/flet_core/locks.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
class NopeLock(object):
class NopeLock():
def __enter__(self):
pass

def __exit__(self, *args):
pass


class AsyncNopeLock(object):
class AsyncNopeLock():
async def __aenter__(self):
pass

Expand Down
24 changes: 12 additions & 12 deletions sdk/python/packages/flet-core/src/flet_core/page.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ def __validate_controls_page(self, added_controls):
for ctrl in added_controls:
if ctrl.page and ctrl.page != self:
raise Exception(
"Control has already been added to another page: {}".format(ctrl)
f"Control has already been added to another page: {ctrl}"
)

def __update_control_ids(self, added_controls, results):
Expand Down Expand Up @@ -486,7 +486,7 @@ def __on_page_change_event(self, data):
self._index[id]._set_attr(name, props[name], dirty=False)

def go(self, route, **kwargs):
self.route = route if kwargs == {} else route + self.query.post(kwargs)
self.route = route if not kwargs else route + self.query.post(kwargs)

self.__on_route_change.get_sync_handler()(
ControlEvent(
Expand All @@ -501,7 +501,7 @@ def go(self, route, **kwargs):
self.query() # Update query url (required when using go)

async def go_async(self, route, **kwargs):
self.route = route if kwargs == {} else route + self.query.post(kwargs)
self.route = route if not kwargs else route + self.query.post(kwargs)

await self.__on_route_change.get_handler()(
ControlEvent(
Expand Down Expand Up @@ -776,13 +776,13 @@ def __get_launch_url_args(
window_height: Optional[int] = None,
):
args = {"url": url}
if web_window_name != None:
if web_window_name is not None:
args["web_window_name"] = web_window_name
if web_popup_window != None:
if web_popup_window is not None:
args["web_popup_window"] = str(web_popup_window)
if window_width != None:
if window_width is not None:
args["window_width"] = str(window_width)
if window_height != None:
if window_height is not None:
args["window_height"] = str(window_height)
return args

Expand Down Expand Up @@ -845,9 +845,9 @@ def invoke_method(
)

result, err = self.__method_call_results.pop(evt)
if err != None:
if err is not None:
raise Exception(err)
if result == None:
if result is None:
return None
return result

Expand Down Expand Up @@ -889,17 +889,17 @@ async def invoke_method_async(
)

result, err = self.__method_call_results.pop(evt)
if err != None:
if err is not None:
raise Exception(err)
if result == None:
if result is None:
return None
return result

def __on_invoke_method_result(self, e):
d = json.loads(e.data)
result = InvokeMethodResults(**d)
evt = self.__method_calls.pop(result.method_id, None)
if evt == None:
if evt is None:
return
self.__method_call_results[evt] = (result.result, result.error)
evt.set()
Expand Down
2 changes: 1 addition & 1 deletion sdk/python/packages/flet-core/src/flet_core/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class Command:
commands: List[Any] = field(default_factory=list)

def __str__(self):
return "{} {} {}".format(self.name, self.values, self.attrs)
return f"{self.name} {self.values} {self.attrs}"


@dataclass
Expand Down
4 changes: 1 addition & 3 deletions sdk/python/packages/flet-core/src/flet_core/querystring.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,10 @@ def _is_encoded(self) -> bool:
if "?" in self.url:
q_result = self._querystring_part()
return (
True
if self._decode_url_component(
self._decode_url_component(
self.url[q_result.start() + 1 : q_result.end()]
)
!= self.url[q_result.start() + 1 : q_result.end()]
else False
)

def _querystring_part(self, url_string: bool = False):
Expand Down
4 changes: 2 additions & 2 deletions sdk/python/packages/flet-core/src/flet_core/row.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,9 +230,9 @@ def scroll(self, value: Optional[ScrollMode]):
self.__set_scroll(value)

def __set_scroll(self, value: Optional[ScrollModeString]):
if value == True:
if value is True:
value = "auto"
elif value == False:
elif value is False:
value = None
self._set_attr("scroll", value)

Expand Down
4 changes: 2 additions & 2 deletions sdk/python/packages/flet-core/src/flet_core/view.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,9 +193,9 @@ def scroll(self, value: Optional[ScrollMode]):
self.__set_scroll(value)

def __set_scroll(self, value: Optional[ScrollModeString]):
if value == True:
if value is True:
value = "auto"
elif value == False:
elif value is False:
value = None
self._set_attr("scroll", value)

Expand Down
1 change: 0 additions & 1 deletion sdk/python/packages/flet-core/tests/test_alert_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,3 @@ def test_alignment_str():
assert isinstance(r._get_attr("actionsalignment"), str)
cmd = r._build_add_commands()
assert cmd[0].attrs["actionsalignment"] == "center"

6 changes: 3 additions & 3 deletions sdk/python/packages/flet-core/tests/test_animated_switcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def test_instance_no_attrs_set():

def test_switch_in_curve_enum():
r = ft.AnimatedSwitcher()
assert r.switch_in_curve == None
assert r.switch_in_curve is None
assert r._get_attr("switchInCurve") is None

r = ft.AnimatedSwitcher(switch_in_curve=ft.AnimationCurve.BOUNCE_IN)
Expand All @@ -34,7 +34,7 @@ def test_switch_in_curve_enum():

def test_switch_out_curve_enum():
r = ft.AnimatedSwitcher()
assert r.switch_out_curve == None
assert r.switch_out_curve is None
assert r._get_attr("switchOutCurve") is None

r = ft.AnimatedSwitcher(switch_out_curve=ft.AnimationCurve.BOUNCE_IN)
Expand All @@ -49,7 +49,7 @@ def test_switch_out_curve_enum():

def test_transition_enum():
r = ft.AnimatedSwitcher()
assert r.transition == None
assert r.transition is None
assert r._get_attr("transition") is None

r = ft.AnimatedSwitcher(transition=ft.AnimatedSwitcherTransition.FADE)
Expand Down
4 changes: 2 additions & 2 deletions sdk/python/packages/flet-core/tests/test_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def test_text_align_enum():

def test_text_style_enum():
r = ft.Text()
assert r.style == None
assert r.style is None
assert r._get_attr("style") is None

r = ft.Text(style=ft.TextThemeStyle.DISPLAY_LARGE)
Expand Down Expand Up @@ -64,7 +64,7 @@ def test_text_overflow_enum():

def test_weight_enum():
r = ft.Text()
assert r.weight == None
assert r.weight is None
assert r._get_attr("weight") is None

r = ft.Text(weight=ft.FontWeight.BOLD)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ async def __on_message(self, data: str):
)
else:
# it's something else
raise Exception('Unknown message "{}": {}'.format(msg.action, msg.payload))
raise Exception(f'Unknown message "{msg.action}": {msg.payload}')

async def send_command_async(self, session_id: str, command: Command):
return self.send_command(session_id, command)
Expand Down
4 changes: 2 additions & 2 deletions sdk/python/packages/flet/src/flet/__pyinstaller/win_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import uuid
from pathlib import Path

import packaging.version as version
from packaging import version
import pefile
import PyInstaller.utils.win32.versioninfo as versioninfo
from PyInstaller.utils.win32 import versioninfo
from PyInstaller.building.icon import normalize_icon_type
from PyInstaller.compat import win32api
from PyInstaller.utils.win32.icon import IconFile, normalize_icon_type
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ async def __receive_loop(self, reader: asyncio.StreamReader):
while True:
try:
raw_msglen = await reader.readexactly(4)
except:
except Exception:
return None

if not raw_msglen:
Expand All @@ -93,8 +93,8 @@ async def __send_loop(self, writer: asyncio.StreamWriter):
msg = struct.pack(">I", len(data)) + data
writer.write(msg)
# await writer.drain()
logger.debug("sent to TCP: {}".format(len(msg)))
except:
logger.debug(f"sent to TCP: {len(msg)}")
except Exception:
# re-enqueue the message to repeat it when re-connected
self.__send_queue.put_nowait(message)
raise
Expand Down Expand Up @@ -128,7 +128,7 @@ async def __on_message(self, data: str):
)
else:
# it's something else
raise Exception('Unknown message "{}": {}'.format(msg.action, msg.payload))
raise Exception(f'Unknown message "{msg.action}": {msg.payload}')

async def send_command_async(self, session_id: str, command: Command):
result, message = self._process_command(command)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ async def __start_loops(self):

# re-connect if one of tasks failed
if failed:
logger.debug(f"Re-connecting to Flet server in 1 second")
logger.debug("Re-connecting to Flet server in 1 second")
await asyncio.sleep(self.__CONNECT_TIMEOUT)
await self.connect()

Expand Down Expand Up @@ -148,7 +148,7 @@ async def __send_loop(self):
message = await self.__send_queue.get()
try:
await self.__ws.send(message)
except:
except Exception:
# re-enqueue the message to repeat it when re-connected
self.__send_queue.put_nowait(message)
raise
Expand Down Expand Up @@ -195,5 +195,5 @@ async def close(self):
if self.__ws:
try:
await self.__ws.close()
except:
except Exception:
pass # do nothing
Loading

0 comments on commit 1725a16

Please sign in to comment.