From d6eede55a8e8fb2665343c8bbe7284e1b14289c7 Mon Sep 17 00:00:00 2001 From: Raphael Nestler Date: Mon, 20 May 2024 16:42:46 +0200 Subject: [PATCH] Replace type comments with type annotations (#130) Also correct type annotations where needed and remove them were the type can be inferred. --- common.py | 4 ++-- entities/component.py | 10 +++++----- entities/device.py | 6 +++--- entities/package.py | 18 +++++++++--------- entities/symbol.py | 10 +++++----- generate_chip.py | 10 +++++----- generate_dfn.py | 2 +- generate_led.py | 2 +- generate_mosfet_dual.py | 4 ++-- generate_so.py | 2 +- generate_stm_mcu.py | 34 +++++++++++++++++----------------- 11 files changed, 51 insertions(+), 51 deletions(-) diff --git a/common.py b/common.py index 7036332..25e81f6 100644 --- a/common.py +++ b/common.py @@ -7,7 +7,7 @@ import re from datetime import datetime -from typing import Any, Dict, Iterable, List, Union +from typing import Any, Dict, Iterable, List, OrderedDict, Union # String escape sequences STRING_ESCAPE_SEQUENCES = ( @@ -24,7 +24,7 @@ def init_cache(uuid_cache_file: str) -> Dict[str, str]: print('Loading cache: {}'.format(uuid_cache_file)) - uuid_cache = collections.OrderedDict() # type: Dict[str, str] + uuid_cache: OrderedDict[str, str] = collections.OrderedDict() try: with open(uuid_cache_file, 'r') as f: reader = csv.reader(f, delimiter=',', quotechar='"') diff --git a/entities/component.py b/entities/component.py index ec1d1a0..847625c 100644 --- a/entities/component.py +++ b/entities/component.py @@ -112,7 +112,7 @@ def __init__(self, uuid: str, symbol_uuid: SymbolUUID, position: Position, self.rotation = rotation self.required = required self.suffix = suffix - self.pins = [] # type: List[PinSignalMap] + self.pins: List[PinSignalMap] = [] def add_pin_signal_map(self, pin_signal_map: PinSignalMap) -> None: self.pins.append(pin_signal_map) @@ -144,7 +144,7 @@ def __init__(self, uuid: str, norm: Norm, name: Name, description: Description, self.norm = norm self.name = name self.description = description - self.gates = [gate] # type: List[Gate] + self.gates = [gate] def add_gate(self, gate_map: Gate) -> None: self.gates.append(gate_map) @@ -178,9 +178,9 @@ def __init__(self, uuid: str, name: Name, description: Description, self.schematic_only = schematic_only self.default_value = default_value self.prefix = prefix - self.signals = [] # type: List[Signal] - self.variants = [] # type: List[Variant] - self.approvals = [] # type: List[str] + self.signals: List[Signal] = [] + self.variants: List[Variant] = [] + self.approvals: List[str] = [] def add_approval(self, approval: str) -> None: self.approvals.append(approval) diff --git a/entities/device.py b/entities/device.py index 2599843..3508ff0 100644 --- a/entities/device.py +++ b/entities/device.py @@ -70,9 +70,9 @@ def __init__(self, uuid: str, name: Name, description: Description, self.categories = categories self.component_uuid = component_uuid self.package_uuid = package_uuid - self.pads = [] # type: List[ComponentPad] - self.parts = [] # type: List[Part] - self.approvals = [] # type: List[str] + self.pads: List[ComponentPad] = [] + self.parts: List[Part] = [] + self.approvals: List[str] = [] def add_pad(self, pad: ComponentPad) -> None: self.pads.append(pad) diff --git a/entities/package.py b/entities/package.py index 51a1aaa..3301f2f 100644 --- a/entities/package.py +++ b/entities/package.py @@ -256,11 +256,11 @@ def __init__(self, uuid: str, name: Name, description: Description, self.description = description self.position_3d = position_3d self.rotation_3d = rotation_3d - self.pads = [] # type: List[FootprintPad] - self.models_3d = [] # type: List[Footprint3DModel] - self.polygons = [] # type: List[Polygon] - self.circles = [] # type: List[Circle] - self.texts = [] # type: List[StrokeText] + self.pads: List[FootprintPad] = [] + self.models_3d: List[Footprint3DModel] = [] + self.polygons: List[Polygon] = [] + self.circles: List[Circle] = [] + self.texts: List[StrokeText] = [] def add_pad(self, pad: FootprintPad) -> None: self.pads.append(pad) @@ -308,10 +308,10 @@ def __init__(self, uuid: str, name: Name, description: Description, self.generated_by = generated_by self.categories = categories self.assembly_type = assembly_type - self.pads = [] # type: List[PackagePad] - self.models_3d = [] # type: List[Package3DModel] - self.footprints = [] # type: List[Footprint] - self.approvals = [] # type: List[str] + self.pads: List[PackagePad] = [] + self.models_3d: List[Package3DModel] = [] + self.footprints: List[Footprint] = [] + self.approvals: List[str] = [] def add_pad(self, pad: PackagePad) -> None: self.pads.append(pad) diff --git a/entities/symbol.py b/entities/symbol.py index 837ddfa..180a888 100644 --- a/entities/symbol.py +++ b/entities/symbol.py @@ -76,11 +76,11 @@ def __init__(self, uuid: str, name: Name, description: Description, self.deprecated = deprecated self.generated_by = generated_by self.categories = categories - self.pins = [] # type: List[Pin] - self.polygons = [] # type: List[Polygon] - self.circles = [] # type: List[Circle] - self.texts = [] # type: List[Text] - self.approvals = [] # type: List[str] + self.pins: List[Pin] = [] + self.polygons: List[Polygon] = [] + self.circles: List[Circle] = [] + self.texts: List[Text] = [] + self.approvals: List[str] = [] def add_pin(self, pin: Pin) -> None: self.pins.append(pin) diff --git a/generate_chip.py b/generate_chip.py index a53486f..780ff1c 100644 --- a/generate_chip.py +++ b/generate_chip.py @@ -9,7 +9,7 @@ from os import path from uuid import uuid4 -from typing import Any, Dict, Iterable, Optional, Tuple +from typing import Dict, Iterable, Optional, Tuple from common import format_ipc_dimension as fd from common import init_cache, now, save_cache @@ -198,10 +198,10 @@ def generate_pkg( ) -> None: category = 'pkg' for config in configs: - fmt_params = { + fmt_params: Dict[str, str] = { 'size_metric': config.size_metric(), 'size_imperial': config.size_imperial(), - } # type: Dict[str, Any] + } fmt_params_name = { **fmt_params, 'length': fd(config.body.length), @@ -699,10 +699,10 @@ def generate_dev( ) -> None: category = 'dev' for (size_metric, size_imperial, pkg_name) in packages: - fmt_params = { + fmt_params: Dict[str, str] = { 'size_metric': size_metric, 'size_imperial': size_imperial, - } # type: Dict[str, Any] + } full_name = name.format(**fmt_params) full_desc = description.format(**fmt_params) + \ "\n\nGenerated with {}".format(generator) diff --git a/generate_dfn.py b/generate_dfn.py index eda4607..0e3ec0c 100644 --- a/generate_dfn.py +++ b/generate_dfn.py @@ -377,7 +377,7 @@ def _generate_footprint(key: str, name: str, pad_extension: float) -> None: if __name__ == '__main__': - generated_packages = [] # type: List[str] + generated_packages: List[str] = [] for config in JEDEC_CONFIGS: # Find out which configs to create diff --git a/generate_led.py b/generate_led.py index 5f51041..0d51d92 100644 --- a/generate_led.py +++ b/generate_led.py @@ -725,7 +725,7 @@ def _uuid(identifier: str) -> str: warning = 'Note: Not generating 3D models unless the "--3d" argument is passed in!' print(f'\033[1;33m{warning}\033[0m') - configs = [] # type: List[LedConfig] + configs: List[LedConfig] = [] # Generic LEDs # diff --git a/generate_mosfet_dual.py b/generate_mosfet_dual.py index 9ffa9a5..382c6f4 100644 --- a/generate_mosfet_dual.py +++ b/generate_mosfet_dual.py @@ -113,10 +113,10 @@ def generate_dev( for fet_config in configs: lines = [] - fmt_params = { + fmt_params: Dict[str, Any] = { 'name': fet_config.name, 'max_voltage': fet_config.max_voltage, - } # type: Dict[str, Any] + } full_name = name.format(**fmt_params) full_desc = description.format(**fmt_params) diff --git a/generate_so.py b/generate_so.py index fbc2b6f..34350d5 100644 --- a/generate_so.py +++ b/generate_so.py @@ -536,7 +536,7 @@ def generate_3d( print(f'\033[1;33m{warning}\033[0m') # SOIC - configs = [] # type: List[SoConfig] + configs: List[SoConfig] = [] for pin_count in [6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 28, 30, 32]: for height in [1.2, 1.4, 1.7, 2.7]: pitch = 1.27 diff --git a/generate_stm_mcu.py b/generate_stm_mcu.py index 0901c64..059ad36 100644 --- a/generate_stm_mcu.py +++ b/generate_stm_mcu.py @@ -30,7 +30,7 @@ from os import listdir, path from uuid import uuid4 -from typing import Any, Dict, Iterable, Iterator, List, Optional, Set, Tuple +from typing import Any, DefaultDict, Dict, Iterable, Iterator, List, Optional, Set, Tuple import common from common import human_sort_key, init_cache, save_cache @@ -101,8 +101,8 @@ def __init__( class SymbolPinPlacement: def __init__(self) -> None: - self.left = [] # type: List[Tuple[str, int]] - self.right = [] # type: List[Tuple[str, int]] + self.left: List[Tuple[str, int]] = [] + self.right: List[Tuple[str, int]] = [] def add_left_pin(self, pin_name: str, y_pos: int) -> None: self.left.append((pin_name, y_pos)) @@ -176,24 +176,24 @@ def __init__(self, ref: str, info: Dict[str, Any], pins: Iterable[Pin]): self.pins = list(pins) self.flash = '{} KiB'.format(info['info']['flash']) self.ram = '{} KiB'.format(info['info']['ram']) - self.io_count = info['info']['io'] # type: int + self.io_count: int = info['info']['io'] self.gpio_version = info['gpio_version'] if len(info['gpio_version']) else None if 'frequency' in info['info']: - self.frequency = '{} MHz'.format(info['info']['frequency']) # type: Optional[str] + self.frequency: Optional[str] = '{} MHz'.format(info['info']['frequency']) else: self.frequency = None if 'voltage' in info['info']: - self.voltage = '{:.2}-{:.2}V'.format( + self.voltage: Optional[str] = '{:.2}-{:.2}V'.format( info['info']['voltage']['min'], info['info']['voltage']['max'], - ) # type: Optional[str] + ) else: self.voltage = None if 'temperature' in info['info']: - self.temperature = '{:.0f}-{:.0f}°C'.format( + self.temperature: Optional[str] = '{:.0f}-{:.0f}°C'.format( info['info']['temperature']['min'], info['info']['temperature']['max'], - ) # type: Optional[str] + ) else: self.temperature = None @@ -228,7 +228,7 @@ def _cleanup_pin_name(pin_name: str) -> str: @classmethod def from_json(cls, ref: str, info: Dict[str, Any]) -> 'MCU': # Collect pins, grouped by number - pin_map = defaultdict(list) # type: Dict[str, List[Pin]] + pin_map: DefaultDict[str, List[Pin]] = defaultdict(list) for entry in info['pinout']: if entry['type'] == 'NC' and len(entry['signals']) == 0: # Skip non-connected pins without signals @@ -241,7 +241,7 @@ def from_json(cls, ref: str, info: Dict[str, Any]) -> 'MCU': pin_map[entry['position']].append(pin) # Merge pins into a flat list - pins = [] # type: List[Pin] + pins: List[Pin] = [] for group in pin_map.values(): # Merge signal names merged_name = '/'.join(sorted((pin.name for pin in group), key=human_sort_key)) @@ -280,7 +280,7 @@ def get_pin_names_by_type(self, pin_type: str) -> List[PinName]: Return all pin names of that type (without duplicates), sorted. """ pins = self.get_pins_by_type(pin_type) - known_names = set() # type: Set[str] + known_names: Set[str] = set() result = [] i = 1 for pin in pins: @@ -814,21 +814,21 @@ def generate_dev(mcu: MCU, symbol_map: Dict[str, str], base_lib_path: str, debug def generate(data: Dict[str, MCU], base_lib_path: str, debug: bool = False) -> None: # A map mapping symbol names to UUIDs - symbol_map = {} # type: Dict[str, str] + symbol_map: Dict[str, str] = {} print('\nProcessing {} MCUs'.format(len(data))) # Group symbols - symbols = defaultdict(list) # type: Dict[str, List[MCU]] + symbols: DefaultDict[str, List[MCU]] = defaultdict(list) for mcu in data.values(): symbols[mcu.symbol_identifier].append(mcu) print('Generating {} symbols'.format(len(symbols))) # Group components - components_tmp = defaultdict(list) # type: Dict[str, List[MCU]] + components_tmp: DefaultDict[str, List[MCU]] = defaultdict(list) for mcu in data.values(): components_tmp[mcu.component_identifier].append(mcu) - components = defaultdict(list) # type: Dict[str, List[MCU]] + components: DefaultDict[str, List[MCU]] = defaultdict(list) for k, v in components_tmp.items(): combined_name = v[0].ref_for_flash_variants([mcu.ref for mcu in v]) components[combined_name] = v @@ -865,7 +865,7 @@ def generate(data: Dict[str, MCU], base_lib_path: str, debug: bool = False) -> N args = parser.parse_args() # Load and parse all data - data = {} # type: Dict[str, MCU] + data: Dict[str, MCU] = {} for filename in listdir(args.data_dir): # Note: Only process STM32 files for now, because the STM8 ref naming scheme is inconsistent. # See https://github.com/LibrePCB-Libraries/STMicroelectronics.lplib/pull/5 for details.