Skip to content

Commit 9947809

Browse files
committed
Auto-format code
1 parent 965dbd2 commit 9947809

File tree

7 files changed

+56
-63
lines changed

7 files changed

+56
-63
lines changed

py/cddl/ast.py

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
"""Abstract Syntax Tree (AST) data structures for CDDL definitions."""
1919

2020
from dataclasses import dataclass, field
21-
from typing import Optional, List, Union
2221

2322

2423
@dataclass
@@ -27,18 +26,18 @@ class CddlField:
2726
name: str
2827
type: "CddlType"
2928
optional: bool = False
30-
description: Optional[str] = None
29+
description: str | None = None
3130

3231

3332
@dataclass
3433
class CddlType:
3534
"""Base class for all CDDL type definitions."""
3635
name: str
3736
base_type: str = "unknown" # Type category: ref, string, number, etc.
38-
module: Optional[str] = None # e.g., "session", "network"
39-
description: Optional[str] = None
40-
reference: Optional[str] = None # For type references
41-
value: Optional[str] = None # For literal values
37+
module: str | None = None # e.g., "session", "network"
38+
description: str | None = None
39+
reference: str | None = None # For type references
40+
value: str | None = None # For literal values
4241
is_primitive: bool = False # Whether this is a primitive type
4342

4443

@@ -51,55 +50,55 @@ class CddlPrimitiveType(CddlType):
5150
@dataclass
5251
class CddlObject(CddlType):
5352
"""Represents a CDDL object type with fields."""
54-
fields: List[CddlField] = field(default_factory=list)
53+
fields: list[CddlField] = field(default_factory=list)
5554
extensible: bool = False # Whether object allows additional fields
5655

5756

5857
@dataclass
5958
class CddlEnum(CddlType):
6059
"""Represents a CDDL enum type with string values."""
61-
values: List[str] = field(default_factory=list)
60+
values: list[str] = field(default_factory=list)
6261

6362

6463
@dataclass
6564
class CddlUnionVariant:
6665
"""Represents one variant in a union type."""
6766
index: int = 0 # Index in union
68-
type: Optional[CddlType] = None # The type for this variant
69-
discriminator_field: Optional[str] = None # For tagged unions
70-
discriminator_value: Optional[str] = None # Value of discriminator field
67+
type: CddlType | None = None # The type for this variant
68+
discriminator_field: str | None = None # For tagged unions
69+
discriminator_value: str | None = None # Value of discriminator field
7170

7271

7372
@dataclass
7473
class CddlUnion(CddlType):
7574
"""Represents a CDDL union type (multiple possible types)."""
76-
variants: List[CddlUnionVariant] = field(default_factory=list)
75+
variants: list[CddlUnionVariant] = field(default_factory=list)
7776

7877

7978
@dataclass
8079
class CddlArray(CddlType):
8180
"""Represents a CDDL array type."""
82-
item_type: Optional[CddlType] = None
81+
item_type: CddlType | None = None
8382

8483

8584
@dataclass
8685
class CddlCommand(CddlType):
8786
"""Represents a WebDriver BiDi command."""
8887
method: str = "" # e.g., "session.new"
89-
params: Optional[CddlObject] = None
90-
result: Optional[CddlObject] = None
88+
params: CddlObject | None = None
89+
result: CddlObject | None = None
9190

9291

9392
@dataclass
9493
class CddlModule:
9594
"""Represents a module grouping (e.g., all session.* types)."""
9695
name: str # e.g., "session", "network"
9796
types: dict = field(default_factory=dict) # Dict[name, CddlType]
98-
commands: List[CddlCommand] = field(default_factory=list)
97+
commands: list[CddlCommand] = field(default_factory=list)
9998

10099

101100
@dataclass
102101
class CddlSpecification:
103102
"""Root node representing entire CDDL specification."""
104-
modules: List[CddlModule] = field(default_factory=list)
103+
modules: list[CddlModule] = field(default_factory=list)
105104
types: dict = field(default_factory=dict) # Dict[name, CddlType] - Global types

py/cddl/downloader.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,15 @@
1919

2020
import re
2121
from pathlib import Path
22-
from typing import Optional
23-
from urllib.request import urlopen
2422
from urllib.error import URLError
23+
from urllib.request import urlopen
2524

2625
# W3C WebDriver BiDi specification URL with CDDL index
2726
W3C_WEBDRIVER_BIDI_URL = "https://www.w3.org/TR/webdriver-bidi/"
2827

2928

3029
def download_cddl_spec(
31-
output_dir: Optional[Path] = None,
30+
output_dir: Path | None = None,
3231
force: bool = False,
3332
) -> Path:
3433
"""Download W3C WebDriver BiDi CDDL specification from HTML spec.
@@ -62,7 +61,7 @@ def download_cddl_spec(
6261
try:
6362
with urlopen(W3C_WEBDRIVER_BIDI_URL) as response:
6463
spec_html = response.read().decode("utf-8")
65-
print(f"Downloaded specification")
64+
print("Downloaded specification")
6665
except URLError as e:
6766
raise URLError(f"Failed to download W3C spec: {e}")
6867

@@ -164,5 +163,5 @@ def read_cddl_file(file_path: Path) -> str:
164163
Returns:
165164
File content as string
166165
"""
167-
with open(file_path, "r", encoding="utf-8") as f:
166+
with open(file_path, encoding="utf-8") as f:
168167
return f.read()

py/cddl/generator.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,7 @@
2020
Generates Python dataclasses, Enums, and Union types from CDDL AST.
2121
"""
2222

23-
from typing import Dict, List, Optional, Tuple, Set
24-
from pathlib import Path
25-
from . import ast
26-
from . import type_guards
23+
from . import ast, type_guards
2724

2825

2926
class PythonCodeGenerator:
@@ -65,8 +62,8 @@ def __init__(self, strict_mode: bool = False):
6562
strict_mode: If True, validate all fields strictly
6663
"""
6764
self.strict_mode = strict_mode
68-
self.type_imports: Set[str] = set()
69-
self.generated_code: Dict[str, str] = {}
65+
self.type_imports: set[str] = set()
66+
self.generated_code: dict[str, str] = {}
7067

7168
def generate_module(self, module: ast.CddlModule) -> str:
7269
"""Generate Python code for an entire module.
@@ -92,7 +89,7 @@ def generate_module(self, module: ast.CddlModule) -> str:
9289

9390
return "\n".join(lines)
9491

95-
def _generate_type(self, cddl_type: ast.CddlType, module_name: str = "") -> Optional[str]:
92+
def _generate_type(self, cddl_type: ast.CddlType, module_name: str = "") -> str | None:
9693
"""Generate Python code for a single type.
9794
9895
Args:
@@ -138,7 +135,7 @@ def _generate_dataclass(self, obj_type: ast.CddlObject) -> str:
138135
if obj_type.description:
139136
lines.append(f' """{obj_type.description}"""')
140137
else:
141-
lines.append(f' """Auto-generated from WebDriver BiDi CDDL."""')
138+
lines.append(' """Auto-generated from WebDriver BiDi CDDL."""')
142139

143140
# Generate fields
144141
if obj_type.fields:
@@ -170,7 +167,7 @@ def _generate_dataclass(self, obj_type: ast.CddlObject) -> str:
170167
lines.append("")
171168
lines.append(" @classmethod")
172169
lines.append(" def from_json(cls, data: Dict[str, Any]) -> '{class_name}':")
173-
lines.append(f" \"\"\"Create from JSON dict with lenient parsing.\"\"\"")
170+
lines.append(" \"\"\"Create from JSON dict with lenient parsing.\"\"\"")
174171
lines.append(" kwargs = {}")
175172
for field in obj_type.fields:
176173
python_name = type_guards._snake_to_camel(field.name)
@@ -192,7 +189,7 @@ def _generate_enum(self, enum_type: ast.CddlEnum) -> str:
192189
"""
193190
class_name = self._sanitize_name(enum_type.name)
194191
lines = [f"class {class_name}(str, Enum):"]
195-
lines.append(f' """Auto-generated enum from WebDriver BiDi CDDL."""')
192+
lines.append(' """Auto-generated enum from WebDriver BiDi CDDL."""')
196193

197194
if enum_type.values:
198195
for i, value in enumerate(enum_type.values):

py/cddl/main.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
import argparse
2121
import logging
2222
from pathlib import Path
23-
from typing import Optional
2423

2524
from . import downloader, parser, writer
2625

@@ -185,12 +184,12 @@ def cmd_parse(args) -> int:
185184
# Parse CDDL
186185
logging.info(f"Parsing {cddl_file}...")
187186
try:
188-
with open(cddl_file, "r") as f:
187+
with open(cddl_file) as f:
189188
cddl_text = f.read()
190189

191190
spec = parser.parse_cddl(cddl_text)
192191

193-
logging.info(f"Successfully parsed CDDL")
192+
logging.info("Successfully parsed CDDL")
194193
logging.info(f" Modules: {len(spec.modules)}")
195194
logging.info(f" Types: {len(spec.types)}")
196195

@@ -199,7 +198,7 @@ def cmd_parse(args) -> int:
199198
logging.info(f" Module '{module.name}': {len(module.types)} types")
200199

201200
if args.output:
202-
logging.info(f"Output to JSON not yet implemented")
201+
logging.info("Output to JSON not yet implemented")
203202

204203
return 0
205204
except SyntaxError as e:
@@ -235,14 +234,14 @@ def cmd_generate(args) -> int:
235234
# Parse CDDL
236235
logging.info(f"Parsing {cddl_file}...")
237236
try:
238-
with open(cddl_file, "r") as f:
237+
with open(cddl_file) as f:
239238
cddl_text = f.read()
240239

241240
spec = parser.parse_cddl(cddl_text)
242241
logging.info(f"Successfully parsed CDDL ({len(spec.types)} types)")
243242

244243
# Generate code
245-
logging.info(f"Generating Python code...")
244+
logging.info("Generating Python code...")
246245
module_writer = writer.ModuleWriter(args.output_dir, strict_mode=args.strict)
247246
written_files = module_writer.write_specification(spec)
248247

@@ -284,7 +283,7 @@ def cmd_generate_all(args) -> int:
284283
# Parse first CDDL file
285284
cddl_file = cddl_files[0]
286285
logging.info(f"Parsing {cddl_file}...")
287-
with open(cddl_file, "r") as f:
286+
with open(cddl_file) as f:
288287
cddl_text = f.read()
289288

290289
spec = parser.parse_cddl(cddl_text)

py/cddl/parser.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919

2020
from dataclasses import dataclass
2121
from enum import Enum, auto
22-
from typing import List, Optional, Set, Dict, Any, Union as UnionType
23-
import re
22+
from typing import Any
23+
2424
from . import ast
2525

2626

@@ -81,9 +81,9 @@ def __init__(self, text: str):
8181
self.pos = 0
8282
self.line = 1
8383
self.column = 1
84-
self.tokens: List[Token] = []
84+
self.tokens: list[Token] = []
8585

86-
def tokenize(self) -> List[Token]:
86+
def tokenize(self) -> list[Token]:
8787
"""Tokenize the CDDL text.
8888
8989
Returns:
@@ -288,7 +288,7 @@ def _make_token(self, token_type: TokenType) -> Token:
288288
class CddlParser:
289289
"""Parser for CDDL specifications."""
290290

291-
def __init__(self, tokens: List[Token]):
291+
def __init__(self, tokens: list[Token]):
292292
"""Initialize parser with token stream.
293293
294294
Args:
@@ -314,7 +314,7 @@ def parse(self) -> dict:
314314
# Skip tokens if parse_definition returned None
315315
# This prevents infinite loops
316316
self._advance()
317-
except SyntaxError as e:
317+
except SyntaxError:
318318
# Skip to next definition on error
319319
# Look for next IDENTIFIER or EXTENSIBLE followed by ASSIGN
320320
while not self._is_at_end():
@@ -353,7 +353,7 @@ def _expect(self, token_type: TokenType) -> Token:
353353
self._advance()
354354
return token
355355

356-
def _parse_definition(self) -> Optional[tuple]:
356+
def _parse_definition(self) -> tuple | None:
357357
"""Parse a CDDL type definition."""
358358
if self._is_at_end():
359359
return None
@@ -558,15 +558,15 @@ def _parse_array(self) -> dict:
558558
class AstTransformer:
559559
"""Transform parsed CDDL dict intermediate representation to AST objects."""
560560

561-
def __init__(self, definitions: Dict[str, Any]):
561+
def __init__(self, definitions: dict[str, Any]):
562562
"""Initialize transformer with parsed definitions.
563563
564564
Args:
565565
definitions: Dictionary of parsed CDDL definitions from CddlParser
566566
"""
567567
self.definitions = definitions
568-
self.cddl_types: Dict[str, ast.CddlType] = {}
569-
self.modules: Dict[str, ast.CddlModule] = {}
568+
self.cddl_types: dict[str, ast.CddlType] = {}
569+
self.modules: dict[str, ast.CddlModule] = {}
570570

571571
def transform(self) -> ast.CddlSpecification:
572572
"""Transform parsed definitions to CddlSpecification AST.
@@ -614,7 +614,7 @@ def _organize_modules(self):
614614
name="_global", types=global_types, commands=[]
615615
)
616616

617-
def _transform_type(self, name: str, definition: Any) -> Optional[ast.CddlType]:
617+
def _transform_type(self, name: str, definition: Any) -> ast.CddlType | None:
618618
"""Transform a single type definition to AST.
619619
620620
Args:
@@ -725,7 +725,7 @@ def _transform_union(self, name: str, definition: dict) -> ast.CddlUnion:
725725
name=name, variants=variants, description=None
726726
)
727727

728-
def _flatten_union_variants(self, definition: dict) -> List[Any]:
728+
def _flatten_union_variants(self, definition: dict) -> list[Any]:
729729
"""Flatten nested union definitions into a list of variants.
730730
731731
Args:

py/cddl/type_guards.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
"""Type guard functions for runtime validation during deserialization."""
1919

20-
from typing import Any, Dict, List, Optional
20+
from typing import Any
2121

2222

2323
def is_string(value: Any) -> bool:
@@ -51,10 +51,10 @@ def is_none(value: Any) -> bool:
5151

5252

5353
def validate_required_field(
54-
json_dict: Dict[str, Any],
54+
json_dict: dict[str, Any],
5555
field_name: str,
5656
expected_type: type,
57-
camel_case: Optional[str] = None,
57+
camel_case: str | None = None,
5858
) -> Any:
5959
"""Validate and extract a required field from JSON.
6060
@@ -86,11 +86,11 @@ def validate_required_field(
8686

8787

8888
def validate_optional_field(
89-
json_dict: Dict[str, Any],
89+
json_dict: dict[str, Any],
9090
field_name: str,
9191
expected_type: type,
9292
default: Any = None,
93-
camel_case: Optional[str] = None,
93+
camel_case: str | None = None,
9494
) -> Any:
9595
"""Validate and extract an optional field from JSON.
9696
@@ -123,11 +123,11 @@ def validate_optional_field(
123123

124124

125125
def validate_object(
126-
json_dict: Dict[str, Any],
127-
required_fields: Dict[str, type],
128-
optional_fields: Optional[Dict[str, type]] = None,
126+
json_dict: dict[str, Any],
127+
required_fields: dict[str, type],
128+
optional_fields: dict[str, type] | None = None,
129129
lenient: bool = True,
130-
) -> Dict[str, Any]:
130+
) -> dict[str, Any]:
131131
"""Validate object fields with lenient or strict mode.
132132
133133
Args:

0 commit comments

Comments
 (0)