Skip to content

Commit 5e836fe

Browse files
committed
chore: switch from using Dict to dict for type hints
Signed-off-by: Tudor Plugaru <[email protected]>
1 parent 53244e1 commit 5e836fe

File tree

6 files changed

+49
-49
lines changed

6 files changed

+49
-49
lines changed

src/cloudevents/core/base.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515

1616
from datetime import datetime
17-
from typing import Any, Dict, Optional, Protocol, Union
17+
from typing import Any, Optional, Protocol, Union
1818

1919

2020
class BaseCloudEvent(Protocol):
@@ -28,8 +28,8 @@ class BaseCloudEvent(Protocol):
2828

2929
def __init__(
3030
self,
31-
attributes: Dict[str, Any],
32-
data: Optional[Union[Dict[str, Any], str, bytes]] = None,
31+
attributes: dict[str, Any],
32+
data: Optional[Union[dict[str, Any], str, bytes]] = None,
3333
) -> None:
3434
"""
3535
Create a new CloudEvent instance.
@@ -115,7 +115,7 @@ def get_extension(self, extension_name: str) -> Any:
115115
"""
116116
...
117117

118-
def get_data(self) -> Optional[Union[Dict[str, Any], str, bytes]]:
118+
def get_data(self) -> Optional[Union[dict[str, Any], str, bytes]]:
119119
"""
120120
Retrieve data of the event.
121121

src/cloudevents/core/bindings/http.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,16 @@
1414

1515
from dataclasses import dataclass
1616
from datetime import datetime
17-
from typing import Any, Callable, Dict, Optional, Union
17+
from typing import Any, Callable, Final, Optional, Union
1818
from urllib.parse import quote, unquote
1919

2020
from dateutil.parser import isoparse
2121

2222
from cloudevents.core.base import BaseCloudEvent
2323
from cloudevents.core.formats.base import Format
2424

25-
CE_PREFIX: str = "ce-"
26-
CONTENT_TYPE_HEADER: str = "content-type"
25+
CE_PREFIX: Final[str] = "ce-"
26+
CONTENT_TYPE_HEADER: Final[str] = "content-type"
2727

2828

2929
@dataclass(frozen=True)
@@ -40,11 +40,11 @@ class HTTPMessage:
4040
body: HTTP body as bytes
4141
"""
4242

43-
headers: Dict[str, str]
43+
headers: dict[str, str]
4444
body: bytes
4545

4646

47-
def _normalize_headers(headers: Dict[str, str]) -> Dict[str, str]:
47+
def _normalize_headers(headers: dict[str, str]) -> dict[str, str]:
4848
"""
4949
Normalize HTTP headers by converting all keys to lowercase.
5050
@@ -116,7 +116,7 @@ def to_binary(event: BaseCloudEvent, event_format: Format) -> HTTPMessage:
116116
:param event_format: Format implementation for data serialization
117117
:return: HTTPMessage with ce-prefixed headers and event data as body
118118
"""
119-
headers: Dict[str, str] = {}
119+
headers: dict[str, str] = {}
120120
attributes = event.get_attributes()
121121

122122
for attr_name, attr_value in attributes.items():
@@ -140,7 +140,7 @@ def from_binary(
140140
message: HTTPMessage,
141141
event_format: Format,
142142
event_factory: Callable[
143-
[Dict[str, Any], Optional[Union[Dict[str, Any], str, bytes]]], BaseCloudEvent
143+
[dict[str, Any], Optional[Union[dict[str, Any], str, bytes]]], BaseCloudEvent
144144
],
145145
) -> BaseCloudEvent:
146146
"""
@@ -168,7 +168,7 @@ def from_binary(
168168
"""
169169
normalized_headers = _normalize_headers(message.headers)
170170

171-
attributes: Dict[str, Any] = {}
171+
attributes: dict[str, Any] = {}
172172

173173
for header_name, header_value in normalized_headers.items():
174174
if header_name.startswith(CE_PREFIX):
@@ -221,7 +221,7 @@ def from_structured(
221221
message: HTTPMessage,
222222
event_format: Format,
223223
event_factory: Callable[
224-
[Dict[str, Any], Optional[Union[Dict[str, Any], str, bytes]]], BaseCloudEvent
224+
[dict[str, Any], Optional[Union[dict[str, Any], str, bytes]]], BaseCloudEvent
225225
],
226226
) -> BaseCloudEvent:
227227
"""
@@ -252,7 +252,7 @@ def from_http(
252252
message: HTTPMessage,
253253
event_format: Format,
254254
event_factory: Callable[
255-
[Dict[str, Any], Optional[Union[Dict[str, Any], str, bytes]]], BaseCloudEvent
255+
[dict[str, Any], Optional[Union[dict[str, Any], str, bytes]]], BaseCloudEvent
256256
],
257257
) -> BaseCloudEvent:
258258
"""

src/cloudevents/core/formats/base.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
# under the License.
1414

1515

16-
from typing import Any, Callable, Dict, Optional, Protocol, Union
16+
from typing import Any, Callable, Optional, Protocol, Union
1717

1818
from cloudevents.core.base import BaseCloudEvent
1919

@@ -31,7 +31,7 @@ class Format(Protocol):
3131
def read(
3232
self,
3333
event_factory: Callable[
34-
[Dict[str, Any], Optional[Union[Dict[str, Any], str, bytes]]],
34+
[dict[str, Any], Optional[Union[dict[str, Any], str, bytes]]],
3535
BaseCloudEvent,
3636
],
3737
data: Union[str, bytes],
@@ -60,7 +60,7 @@ def write(self, event: BaseCloudEvent) -> bytes:
6060

6161
def write_data(
6262
self,
63-
data: Optional[Union[Dict[str, Any], str, bytes]],
63+
data: Optional[Union[dict[str, Any], str, bytes]],
6464
datacontenttype: Optional[str],
6565
) -> bytes:
6666
"""
@@ -74,7 +74,7 @@ def write_data(
7474

7575
def read_data(
7676
self, body: bytes, datacontenttype: Optional[str]
77-
) -> Optional[Union[Dict[str, Any], str, bytes]]:
77+
) -> Optional[Union[dict[str, Any], str, bytes]]:
7878
"""
7979
Deserialize data payload from protocol bindings (e.g., HTTP binary mode).
8080

src/cloudevents/core/formats/json.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
import re
1818
from datetime import datetime
1919
from json import JSONEncoder, dumps, loads
20-
from typing import Any, Callable, Dict, Final, Optional, Pattern, Union
20+
from typing import Any, Callable, Final, Optional, Pattern, Union
2121

2222
from dateutil.parser import isoparse
2323

@@ -51,7 +51,7 @@ class JSONFormat(Format):
5151
def read(
5252
self,
5353
event_factory: Callable[
54-
[Dict[str, Any], Optional[Union[Dict[str, Any], str, bytes]]],
54+
[dict[str, Any], Optional[Union[dict[str, Any], str, bytes]]],
5555
BaseCloudEvent,
5656
],
5757
data: Union[str, bytes],
@@ -74,7 +74,7 @@ def read(
7474
if "time" in event_attributes:
7575
event_attributes["time"] = isoparse(event_attributes["time"])
7676

77-
event_data: Union[Dict[str, Any], str, bytes, None] = event_attributes.pop(
77+
event_data: Union[dict[str, Any], str, bytes, None] = event_attributes.pop(
7878
"data", None
7979
)
8080
if event_data is None:
@@ -108,7 +108,7 @@ def write(self, event: BaseCloudEvent) -> bytes:
108108

109109
def write_data(
110110
self,
111-
data: Optional[Union[Dict[str, Any], str, bytes]],
111+
data: Optional[Union[dict[str, Any], str, bytes]],
112112
datacontenttype: Optional[str],
113113
) -> bytes:
114114
"""
@@ -144,7 +144,7 @@ def write_data(
144144

145145
def read_data(
146146
self, body: bytes, datacontenttype: Optional[str]
147-
) -> Optional[Union[Dict[str, Any], str, bytes]]:
147+
) -> Optional[Union[dict[str, Any], str, bytes]]:
148148
"""
149149
Deserialize data payload from HTTP binary mode body.
150150
@@ -164,7 +164,7 @@ def read_data(
164164
):
165165
try:
166166
decoded = body.decode("utf-8")
167-
parsed: Dict[str, Any] = loads(decoded)
167+
parsed: dict[str, Any] = loads(decoded)
168168
return parsed
169169
except (ValueError, UnicodeDecodeError):
170170
# If JSON parsing fails, fall through to other handling

src/cloudevents/core/v1/event.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
import re
1616
from collections import defaultdict
1717
from datetime import datetime
18-
from typing import Any, Dict, Final, List, Optional, Union
18+
from typing import Any, Final, Optional, Union
1919

2020
from cloudevents.core.base import BaseCloudEvent
2121
from cloudevents.core.v1.exceptions import (
@@ -39,15 +39,15 @@
3939
class CloudEvent(BaseCloudEvent):
4040
def __init__(
4141
self,
42-
attributes: Dict[str, Any],
43-
data: Optional[Union[Dict[str, Any], str, bytes]] = None,
42+
attributes: dict[str, Any],
43+
data: Optional[Union[dict[str, Any], str, bytes]] = None,
4444
) -> None:
4545
self._validate_attribute(attributes=attributes)
46-
self._attributes: Dict[str, Any] = attributes
47-
self._data: Optional[Union[Dict[str, Any], str, bytes]] = data
46+
self._attributes: dict[str, Any] = attributes
47+
self._data: Optional[Union[dict[str, Any], str, bytes]] = data
4848

4949
@staticmethod
50-
def _validate_attribute(attributes: Dict[str, Any]) -> None:
50+
def _validate_attribute(attributes: dict[str, Any]) -> None:
5151
"""
5252
Validates the attributes of the CloudEvent as per the CloudEvents specification.
5353
@@ -62,15 +62,15 @@ def _validate_attribute(attributes: Dict[str, Any]) -> None:
6262

6363
@staticmethod
6464
def _validate_required_attributes(
65-
attributes: Dict[str, Any],
66-
) -> Dict[str, List[BaseCloudEventException]]:
65+
attributes: dict[str, Any],
66+
) -> dict[str, list[BaseCloudEventException]]:
6767
"""
6868
Validates the types of the required attributes.
6969
7070
:param attributes: The attributes of the CloudEvent instance.
7171
:return: A dictionary of validation error messages.
7272
"""
73-
errors: Dict[str, List[BaseCloudEventException]] = defaultdict(list)
73+
errors: dict[str, list[BaseCloudEventException]] = defaultdict(list)
7474

7575
if "id" not in attributes:
7676
errors["id"].append(MissingRequiredAttributeError(attribute_name="id"))
@@ -122,15 +122,15 @@ def _validate_required_attributes(
122122

123123
@staticmethod
124124
def _validate_optional_attributes(
125-
attributes: Dict[str, Any],
126-
) -> Dict[str, List[BaseCloudEventException]]:
125+
attributes: dict[str, Any],
126+
) -> dict[str, list[BaseCloudEventException]]:
127127
"""
128128
Validates the types and values of the optional attributes.
129129
130130
:param attributes: The attributes of the CloudEvent instance.
131131
:return: A dictionary of validation error messages.
132132
"""
133-
errors: Dict[str, List[BaseCloudEventException]] = defaultdict(list)
133+
errors: dict[str, list[BaseCloudEventException]] = defaultdict(list)
134134

135135
if "time" in attributes:
136136
if not isinstance(attributes["time"], datetime):
@@ -192,15 +192,15 @@ def _validate_optional_attributes(
192192

193193
@staticmethod
194194
def _validate_extension_attributes(
195-
attributes: Dict[str, Any],
196-
) -> Dict[str, List[BaseCloudEventException]]:
195+
attributes: dict[str, Any],
196+
) -> dict[str, list[BaseCloudEventException]]:
197197
"""
198198
Validates the extension attributes.
199199
200200
:param attributes: The attributes of the CloudEvent instance.
201201
:return: A dictionary of validation error messages.
202202
"""
203-
errors: Dict[str, List[BaseCloudEventException]] = defaultdict(list)
203+
errors: dict[str, list[BaseCloudEventException]] = defaultdict(list)
204204
extension_attributes = [
205205
key
206206
for key in attributes.keys()
@@ -257,8 +257,8 @@ def get_time(self) -> Optional[datetime]:
257257
def get_extension(self, extension_name: str) -> Any:
258258
return self._attributes.get(extension_name)
259259

260-
def get_data(self) -> Optional[Union[Dict[str, Any], str, bytes]]:
260+
def get_data(self) -> Optional[Union[dict[str, Any], str, bytes]]:
261261
return self._data
262262

263-
def get_attributes(self) -> Dict[str, Any]:
263+
def get_attributes(self) -> dict[str, Any]:
264264
return self._attributes

tests/test_core/test_bindings/test_http.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
# under the License.
1414

1515
from datetime import datetime, timezone
16-
from typing import Any, Callable, Dict, Optional, Union
16+
from typing import Any, Optional, Union
1717

1818
import pytest
1919

@@ -30,7 +30,7 @@
3030

3131

3232
@pytest.fixture
33-
def minimal_attributes() -> Dict[str, str]:
33+
def minimal_attributes() -> dict[str, str]:
3434
"""Minimal valid CloudEvent attributes"""
3535
return {
3636
"type": "com.example.test",
@@ -41,11 +41,11 @@ def minimal_attributes() -> Dict[str, str]:
4141

4242

4343
def create_event(
44-
extra_attrs: Optional[Dict[str, Any]] = None,
45-
data: Optional[Union[Dict[str, Any], str, bytes]] = None,
44+
extra_attrs: Optional[dict[str, Any]] = None,
45+
data: Optional[Union[dict[str, Any], str, bytes]] = None,
4646
) -> CloudEvent:
4747
"""Helper to create CloudEvent with valid required attributes"""
48-
attrs: Dict[str, Any] = {
48+
attrs: dict[str, Any] = {
4949
"type": "com.example.test",
5050
"source": "/test",
5151
"id": "test-id-123",
@@ -68,10 +68,10 @@ def test_http_message_immutable() -> None:
6868
message = HTTPMessage(headers={"test": "value"}, body=b"data")
6969

7070
with pytest.raises(Exception): # FrozenInstanceError
71-
message.headers = {"new": "dict"} # type: ignore[misc]
71+
message.headers = {"new": "dict"}
7272

7373
with pytest.raises(Exception): # FrozenInstanceError
74-
message.body = b"new data" # type: ignore[misc]
74+
message.body = b"new data"
7575

7676

7777
def test_http_message_with_empty_headers() -> None:
@@ -908,7 +908,7 @@ def test_custom_event_factory() -> None:
908908
"""Test using custom event factory function"""
909909

910910
def custom_factory(
911-
attributes: Dict[str, Any], data: Optional[Union[Dict[str, Any], str, bytes]]
911+
attributes: dict[str, Any], data: Optional[Union[dict[str, Any], str, bytes]]
912912
) -> CloudEvent:
913913
# Custom factory that adds a prefix to the type
914914
attributes["type"] = f"custom.{attributes.get('type', 'unknown')}"

0 commit comments

Comments
 (0)