Skip to content

Commit 27d0580

Browse files
authored
Merge pull request #214 from robotpy/lint-and-upgrade
Upgrade syntax and remove unused imports
2 parents 29d68a8 + 9403e7c commit 27d0580

File tree

14 files changed

+58
-67
lines changed

14 files changed

+58
-67
lines changed

docs/conf.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/env python3
2-
# -*- coding: utf-8 -*-
32

43
import sys
54
import os
@@ -46,15 +45,15 @@
4645

4746
intersphinx_mapping = {
4847
"commandsv1": (
49-
"https://robotpy.readthedocs.io/projects/commands-v1/en/%s/" % rtd_version,
48+
f"https://robotpy.readthedocs.io/projects/commands-v1/en/{rtd_version}/",
5049
None,
5150
),
5251
"networktables": (
53-
"https://robotpy.readthedocs.io/projects/pynetworktables/en/%s/" % rtd_version,
52+
f"https://robotpy.readthedocs.io/projects/pynetworktables/en/{rtd_version}/",
5453
None,
5554
),
5655
"wpilib": (
57-
"https://robotpy.readthedocs.io/projects/wpilib/en/%s/" % rtd_version,
56+
f"https://robotpy.readthedocs.io/projects/wpilib/en/{rtd_version}/",
5857
None,
5958
),
6059
}

magicbot/inject.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import logging
2-
from typing import Any, Dict, Optional
2+
from typing import Any, Optional
33

44
logger = logging.getLogger(__name__)
55

@@ -9,8 +9,8 @@ class MagicInjectError(ValueError):
99

1010

1111
def get_injection_requests(
12-
type_hints: Dict[str, type], cname: str, component: Optional[Any] = None
13-
) -> Dict[str, type]:
12+
type_hints: dict[str, type], cname: str, component: Optional[Any] = None
13+
) -> dict[str, type]:
1414
"""
1515
Given a dict of type hints, filter it to the requested injection types.
1616
@@ -52,8 +52,8 @@ def get_injection_requests(
5252

5353

5454
def find_injections(
55-
requests: Dict[str, type], injectables: Dict[str, Any], cname: str
56-
) -> Dict[str, Any]:
55+
requests: dict[str, type], injectables: dict[str, Any], cname: str
56+
) -> dict[str, Any]:
5757
"""
5858
Get a dict of the variables to inject into a given component.
5959
@@ -73,15 +73,13 @@ def find_injections(
7373
# Raise error if injectable syntax used but no injectable was found.
7474
if injectable is None:
7575
raise MagicInjectError(
76-
"Component %s has variable %s (type %s), which is absent from robot"
77-
% (cname, n, inject_type)
76+
f"Component {cname} has variable {n} (type {inject_type}), which is absent from robot"
7877
)
7978

8079
# Raise error if injectable declared with type different than the initial type
8180
if not isinstance(injectable, inject_type):
8281
raise MagicInjectError(
83-
"Component %s variable %s does not match type in robot! (Got %s, expected %s)"
84-
% (cname, n, type(injectable), inject_type)
82+
f"Component {cname} variable {n} does not match type in robot! (Got {type(injectable)}, expected {inject_type})"
8583
)
8684

8785
to_inject[n] = injectable

magicbot/magic_reset.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Any, Dict, Generic, TypeVar
1+
from typing import Any, Generic, TypeVar
22

33
V = TypeVar("V")
44

@@ -36,7 +36,7 @@ def __init__(self, default: V) -> None:
3636
self.default = default
3737

3838

39-
def collect_resets(cls: type) -> Dict[str, Any]:
39+
def collect_resets(cls: type) -> dict[str, Any]:
4040
"""
4141
Get all the ``will_reset_to`` variables and their values from a class.
4242

magicbot/magic_tunable.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
import inspect
44
import typing
55
import warnings
6-
from typing import Callable, Generic, Optional, Sequence, TypeVar, Union, overload
6+
from typing import Callable, Generic, Optional, TypeVar, Union, overload
7+
from collections.abc import Sequence
78

89
import ntcore
910
from ntcore import NetworkTableInstance
@@ -185,9 +186,9 @@ def setup_tunables(component, cname: str, prefix: Optional[str] = "components")
185186
cls = component.__class__
186187

187188
if prefix is None:
188-
prefix = "/%s" % cname
189+
prefix = f"/{cname}"
189190
else:
190-
prefix = "/%s/%s" % (prefix, cname)
191+
prefix = f"/{prefix}/{cname}"
191192

192193
NetworkTables = NetworkTableInstance.getDefault()
193194

@@ -202,9 +203,9 @@ def setup_tunables(component, cname: str, prefix: Optional[str] = "components")
202203
continue
203204

204205
if prop._ntsubtable:
205-
key = "%s/%s/%s" % (prefix, prop._ntsubtable, n)
206+
key = f"{prefix}/{prop._ntsubtable}/{n}"
206207
else:
207-
key = "%s/%s" % (prefix, n)
208+
key = f"{prefix}/{n}"
208209

209210
topic = prop._topic_type(NetworkTables.getTopic(key))
210211
ntvalue = topic.getEntry(prop._ntdefault)
@@ -344,9 +345,9 @@ def collect_feedbacks(component, cname: str, prefix: Optional[str] = "components
344345
.. note:: This isn't useful for normal use.
345346
"""
346347
if prefix is None:
347-
prefix = "/%s" % cname
348+
prefix = f"/{cname}"
348349
else:
349-
prefix = "/%s/%s" % (prefix, cname)
350+
prefix = f"/{prefix}/{cname}"
350351

351352
nt = NetworkTableInstance.getDefault().getTable(prefix)
352353
feedbacks = []

magicbot/magicrobot.py

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import types
66
import typing
77

8-
from typing import Any, Callable, Dict, List, Tuple
8+
from typing import Any, Callable
99

1010
import hal
1111
import wpilib
@@ -72,9 +72,9 @@ def __init__(self) -> None:
7272

7373
self.__last_error_report = -10
7474

75-
self._components: List[Tuple[str, Any]] = []
76-
self._feedbacks: List[Tuple[Callable[[], Any], Callable[[Any], Any]]] = []
77-
self._reset_components: List[Tuple[Dict[str, Any], Any]] = []
75+
self._components: list[tuple[str, Any]] = []
76+
self._feedbacks: list[tuple[Callable[[], Any], Callable[[Any], Any]]] = []
77+
self._reset_components: list[tuple[dict[str, Any], Any]] = []
7878

7979
self.__done = False
8080

@@ -125,7 +125,7 @@ def robotInit(self) -> None:
125125

126126
self.watchdog = SimpleWatchdog(self.control_loop_wait_time)
127127

128-
self.__periodics: List[Tuple[Callable[[], None], str]] = [
128+
self.__periodics: list[tuple[Callable[[], None], str]] = [
129129
(self.robotPeriodic, "robotPeriodic()"),
130130
]
131131

@@ -397,7 +397,7 @@ def autonomous(self) -> None:
397397
except:
398398
self.onException(forceReport=True)
399399

400-
auto_functions: Tuple[Callable[[], None], ...] = (self._enabled_periodic,)
400+
auto_functions: tuple[Callable[[], None], ...] = (self._enabled_periodic,)
401401

402402
if self.use_teleop_in_autonomous:
403403
auto_functions = (self.teleopPeriodic,) + auto_functions
@@ -609,8 +609,7 @@ def _create_components(self) -> None:
609609
# If the type is not actually a type, give a meaningful error
610610
if not isinstance(ctyp, type):
611611
raise TypeError(
612-
"%s has a non-type annotation on %s (%r); lone non-injection variable annotations are disallowed, did you want to assign a static variable?"
613-
% (cls.__name__, m, ctyp)
612+
f"{cls.__name__} has a non-type annotation on {m} ({ctyp!r}); lone non-injection variable annotations are disallowed, did you want to assign a static variable?"
614613
)
615614

616615
component = self._create_component(m, ctyp, injectables)
@@ -650,7 +649,7 @@ def _create_components(self) -> None:
650649

651650
self._components = components
652651

653-
def _collect_injectables(self) -> Dict[str, Any]:
652+
def _collect_injectables(self) -> dict[str, Any]:
654653
injectables = {}
655654
cls = type(self)
656655

@@ -673,7 +672,7 @@ def _collect_injectables(self) -> Dict[str, Any]:
673672

674673
return injectables
675674

676-
def _create_component(self, name: str, ctyp: type, injectables: Dict[str, Any]):
675+
def _create_component(self, name: str, ctyp: type, injectables: dict[str, Any]):
677676
type_hints = typing.get_type_hints(ctyp.__init__)
678677
NoneType = type(None)
679678
init_return_type = type_hints.pop("return", NoneType)
@@ -690,8 +689,7 @@ def _create_component(self, name: str, ctyp: type, injectables: Dict[str, Any]):
690689
# Ensure that mandatory methods are there
691690
if not callable(getattr(component, "execute", None)):
692691
raise ValueError(
693-
"Component %s (%r) must have a method named 'execute'"
694-
% (name, component)
692+
f"Component {name} ({component!r}) must have a method named 'execute'"
695693
)
696694

697695
# Automatically inject a logger object
@@ -701,7 +699,7 @@ def _create_component(self, name: str, ctyp: type, injectables: Dict[str, Any]):
701699

702700
return component
703701

704-
def _setup_vars(self, cname: str, component, injectables: Dict[str, Any]) -> None:
702+
def _setup_vars(self, cname: str, component, injectables: dict[str, Any]) -> None:
705703
self.logger.debug("Injecting magic variables into %s", cname)
706704

707705
type_hints = typing.get_type_hints(type(component))

magicbot/state_machine.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,15 @@
1-
import functools
21
import inspect
32
import logging
43
from typing import (
54
Any,
65
Callable,
76
ClassVar,
8-
Dict,
97
NoReturn,
108
Optional,
11-
Sequence,
129
Union,
1310
overload,
1411
)
12+
from collections.abc import Sequence
1513

1614
import wpilib
1715

@@ -85,7 +83,7 @@ def __init__(
8583

8684
if invalid_args:
8785
raise ValueError(
88-
"Invalid parameter names in %s: %s" % (name, ",".join(invalid_args))
86+
"Invalid parameter names in {}: {}".format(name, ",".join(invalid_args))
8987
)
9088

9189
self.name = name
@@ -136,7 +134,7 @@ def __set_name__(self, owner: type, name: str) -> None:
136134
class _StateData:
137135
def __init__(self, wrapper: _State) -> None:
138136
self.name = wrapper.name
139-
self.duration_attr = "%s_duration" % self.name
137+
self.duration_attr = f"{self.name}_duration"
140138
self.expires: float = 0xFFFFFFFF
141139
self.ran = False
142140
self.run = wrapper.run
@@ -261,7 +259,7 @@ def default_state(f: StateMethod) -> _State:
261259
return _State(f, first=False, must_finish=True, is_default=True)
262260

263261

264-
def _get_class_members(cls: type) -> Dict[str, Any]:
262+
def _get_class_members(cls: type) -> dict[str, Any]:
265263
"""Get the members of the given class in definition order, bases first."""
266264
d = {}
267265
for cls in reversed(cls.__mro__):

robotpy_ext/autonomous/selector.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
import logging
44
import os
55
from glob import glob
6-
from typing import Callable, Sequence, Union
6+
from typing import Callable, Union
7+
from collections.abc import Sequence
78

89
import hal
910
import wpilib
@@ -151,7 +152,7 @@ def __init__(self, autonomous_pkgname, *args, **kwargs):
151152
if mode_name in self.modes:
152153
if not wpilib.DriverStation.isFMSAttached():
153154
raise RuntimeError(
154-
"Duplicate name %s in %s" % (mode_name, module_filename)
155+
f"Duplicate name {mode_name} in {module_filename}"
155156
)
156157

157158
logger.error(
@@ -195,8 +196,9 @@ def __init__(self, autonomous_pkgname, *args, **kwargs):
195196
elif len(default_modes) != 1:
196197
if not wpilib.DriverStation.isFMSAttached():
197198
raise RuntimeError(
198-
"More than one autonomous mode was specified as default! (modes: %s)"
199-
% (", ".join(default_modes))
199+
"More than one autonomous mode was specified as default! (modes: {})".format(
200+
", ".join(default_modes)
201+
)
200202
)
201203

202204
# must PutData after setting up objects

robotpy_ext/autonomous/stateful_autonomous.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def __init__(self, f: Callable, first: bool):
3939
)
4040
if arg.kind is arg.KEYWORD_ONLY:
4141
raise ValueError(
42-
"Cannot use keyword-only parameters for function %s" % name
42+
f"Cannot use keyword-only parameters for function {name}"
4343
)
4444
if arg.name in allowed_args:
4545
args.append(arg.name)
@@ -48,7 +48,7 @@ def __init__(self, f: Callable, first: bool):
4848

4949
if invalid_args:
5050
raise ValueError(
51-
"Invalid parameter names in %s: %s" % (name, ",".join(invalid_args))
51+
"Invalid parameter names in {}: {}".format(name, ",".join(invalid_args))
5252
)
5353

5454
functools.update_wrapper(self, f)
@@ -271,22 +271,22 @@ def register_sd_var(self, name, default, add_prefix=True, vmin=-1, vmax=1):
271271

272272
# communicate the min/max value for numbers to the dashboard
273273
if is_number:
274-
name = "%s|%0.3f|%0.3f" % (name, vmin, vmax)
274+
name = f"{name}|{vmin:0.3f}|{vmax:0.3f}"
275275

276276
self.__tunables.append(name)
277277
self.__table.putStringArray(self.MODE_NAME + "_tunables", self.__tunables)
278278

279279
def __register_sd_var_internal(self, name, default, add_prefix, readback):
280280
if " " in name:
281281
raise ValueError(
282-
"ERROR: Cannot use spaces in a tunable variable name (%s)" % name
282+
f"ERROR: Cannot use spaces in a tunable variable name ({name})"
283283
)
284284

285285
is_number = False
286286
sd_name = name
287287

288288
if add_prefix:
289-
sd_name = "%s\\%s" % (self.MODE_NAME, name)
289+
sd_name = f"{self.MODE_NAME}\\{name}"
290290

291291
if isinstance(default, bool):
292292
self.__table.putBoolean(sd_name, default)

robotpy_ext/common_drivers/distance_sensors_sim.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import math
2-
import wpilib
32

43
from wpilib.simulation import AnalogInputSim
54

robotpy_ext/common_drivers/driver_base.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
class DriverBase(object):
1+
class DriverBase:
22
"""
33
This should be the base class for all drivers in the cdl,
44
currently all it does is spit out a warning message if the driver has not been verified.
@@ -16,7 +16,5 @@ def __init__(self):
1616
"""
1717
if not self.verified:
1818
print(
19-
"Warning, device driver {} has not been verified yet, please use with caution!".format(
20-
self.__class__.__name__
21-
)
19+
f"Warning, device driver {self.__class__.__name__} has not been verified yet, please use with caution!"
2220
)

robotpy_ext/common_drivers/units.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
class Unit(object):
1+
class Unit:
22
"""The class for all of the units here"""
33

44
def __init__(self, base_unit, base_to_unit, unit_to_base):

robotpy_ext/misc/orderedclass.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""
2-
Taken from the python documentation, distributed under
3-
that same license
2+
Taken from the python documentation, distributed under
3+
that same license
44
"""
55

66
import collections

robotpy_ext/misc/simple_watchdog.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import wpilib
22
import logging
3-
from typing import List, Tuple
43

54
logger = logging.getLogger("simple_watchdog")
65

@@ -38,7 +37,7 @@ def __init__(self, timeout: float):
3837
self._expirationTime = 0 # us
3938
self._lastTimeoutPrintTime = 0 # us
4039
self._lastEpochsPrintTime = 0 # us
41-
self._epochs: List[Tuple[str, int]] = []
40+
self._epochs: list[tuple[str, int]] = []
4241

4342
def getTime(self) -> float:
4443
"""Returns the time in seconds since the watchdog was last fed."""

0 commit comments

Comments
 (0)