Skip to content

Commit 536b91a

Browse files
sebixaaronkaplan
authored andcommitted
Upgrade code with pyupgrade --py39-plus
1 parent cb0ab55 commit 536b91a

File tree

24 files changed

+52
-60
lines changed

24 files changed

+52
-60
lines changed

intelmq/bots/collectors/mail/collector_mail_body.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
"""
77
Uses the common mail iteration method from the lib file.
88
"""
9-
from typing import Union, Iterable
9+
from typing import Union
10+
from collections.abc import Iterable
1011

1112
from ._lib import MailCollectorBot
1213

intelmq/bots/collectors/shodan/collector_stream.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
class ShodanStreamCollectorBot(CollectorBot):
3131
"Collect the Shodan stream from the Shodan API"
3232
api_key: str = "<INSERT your API key>"
33-
countries: List[str] = []
33+
countries: list[str] = []
3434
alert: Optional[str] = None
3535

3636
def init(self):

intelmq/bots/experts/gethostbyname/expert.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
class GethostbynameExpertBot(ExpertBot):
3434
"""Resolve the IP address for the FQDN"""
3535
fallback_to_url: bool = True
36-
gaierrors_to_ignore: Tuple[int] = ()
36+
gaierrors_to_ignore: tuple[int] = ()
3737
overwrite: bool = False
3838

3939
def init(self):

intelmq/bots/experts/http/expert_status.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ class HttpStatusExpertBot(ExpertBot):
2424
Specifies if an existing 'status' value should be overwritten.
2525
"""
2626
field: str = "source.url" # The field containing the URL
27-
success_status_codes: List[int] = [] # A list of status codes for success
27+
success_status_codes: list[int] = [] # A list of status codes for success
2828
overwrite: bool = True
2929

3030
def process(self):

intelmq/bots/experts/jinja/expert.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@ class JinjaExpertBot(ExpertBot):
2727
extra.somejinjaoutput: file:///etc/intelmq/somejinjatemplate.j2
2828
"""
2929

30-
fields: Dict[str, str] = {}
31-
_templates: Dict[str, Union[str, Template]] = {}
30+
fields: dict[str, str] = {}
31+
_templates: dict[str, Union[str, Template]] = {}
3232
overwrite: bool = False
3333

3434
def init(self):

intelmq/bots/experts/sieve/expert.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ def process(self) -> None:
173173

174174
_date_op_map = {":before": operator.lt, ":after": operator.gt}
175175

176-
_cond_map: Dict[
176+
_cond_map: dict[
177177
str,
178178
Callable[
179179
[

intelmq/bots/experts/threshold/expert.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,8 @@
4444
messages seen (which will be the threshold value).
4545
4646
"""
47-
from typing import Iterable, Optional
47+
from typing import Optional
48+
from collections.abc import Iterable
4849

4950
from intelmq.lib.bot import ExpertBot
5051
from intelmq.lib.exceptions import ConfigurationError

intelmq/bots/experts/url/expert.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ class URLExpertBot(ExpertBot):
6666
"""
6767

6868
overwrite: bool = False
69-
skip_fields: Optional[List[str]] = None
69+
skip_fields: Optional[list[str]] = None
7070

7171
def init(self):
7272
if self.skip_fields is None:

intelmq/bots/experts/url2fqdn/expert.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def init(self):
2121
warnings.warn(DEPRECATION_WARNING, DeprecationWarning)
2222

2323
@staticmethod
24-
def check(parameters: dict) -> Optional[List[List[str]]]:
24+
def check(parameters: dict) -> Optional[list[list[str]]]:
2525
return [["warning", DEPRECATION_WARNING]]
2626

2727
def process(self):

intelmq/bots/outputs/cif3/output.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ class CIF3OutputBot(OutputBot):
8383
add_feed_provider_as_tag: bool = False
8484
cif3_feed_confidence: float = 5
8585
cif3_static_confidence: bool = False
86-
cif3_additional_tags: List[str] = []
86+
cif3_additional_tags: list[str] = []
8787
cif3_token: Optional[str] = None
8888
cif3_url: Optional[str] = None
8989
fireball: int = 500

intelmq/bots/outputs/restapi/output.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
# SPDX-License-Identifier: AGPL-3.0-or-later
44

55
# -*- coding: utf-8 -*-
6-
from typing import Iterable
6+
from collections.abc import Iterable
77

88
try:
99
import requests

intelmq/bots/outputs/templated_smtp/output.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ class TemplatedSMTPOutputBot(OutputBot):
112112
username: Optional[str] = None
113113
password: Optional[str] = None
114114
verify_cert: bool = True
115-
attachments: List[str] = []
115+
attachments: list[str] = []
116116
mail_from: Optional[str] = None
117117
mail_to: Optional[str] = None
118118
subject: str = "IntelMQ event"

intelmq/bots/parsers/generic/parser_csv.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@
1919
import csv
2020
import json
2121
import re
22-
from typing import Optional, Union, Iterable
22+
from typing import Optional, Union
23+
from collections.abc import Iterable
2324

2425
from intelmq.lib import utils
2526
from intelmq.lib.bot import ParserBot

intelmq/bots/parsers/ioc_extractor/parser.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@
2323
import re
2424
import pkg_resources
2525

26-
from typing import Optional, Iterable
26+
from typing import Optional
27+
from collections.abc import Iterable
2728

2829
from intelmq.lib.bot import ParserBot, utils
2930
from intelmq.lib.exceptions import InvalidArgument

intelmq/bots/parsers/shadowserver/_config.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -128,11 +128,11 @@ def enable_auto_update(enable):
128128
__config.auto_update = enable
129129

130130

131-
def get_feed_by_feedname(given_feedname: str) -> Optional[Tuple[str, Dict[str, Any]]]:
131+
def get_feed_by_feedname(given_feedname: str) -> Optional[tuple[str, dict[str, Any]]]:
132132
return __config.feedname_mapping.get(given_feedname, None)
133133

134134

135-
def get_feed_by_filename(given_filename: str) -> Optional[Tuple[str, Dict[str, Any]]]:
135+
def get_feed_by_filename(given_filename: str) -> Optional[tuple[str, dict[str, Any]]]:
136136
return __config.filename_mapping.get(given_filename, None)
137137

138138

@@ -164,7 +164,7 @@ def convert_float(value: str) -> Optional[float]:
164164
return float(value) if value else None
165165

166166

167-
def convert_http_host_and_url(value: str, row: Dict[str, str]) -> str:
167+
def convert_http_host_and_url(value: str, row: dict[str, str]) -> str:
168168
"""
169169
URLs are split into hostname and path. The column names differ in reports.
170170
Compromised-Website: http_host, url
@@ -282,7 +282,7 @@ def scan_exchange_identifier(field):
282282
return 'vulnerable-exchange-server'
283283

284284

285-
def category_or_detail(value: str, row: Dict[str, str]) -> str:
285+
def category_or_detail(value: str, row: dict[str, str]) -> str:
286286
"""
287287
Returns the category or detail field from the row.
288288
"""

intelmq/bots/parsers/shodan/parser.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -460,7 +460,7 @@ def __repr__(self) -> str:
460460
}
461461

462462

463-
def _keys_conversion(x: Dict[str, Any]) -> List[str]:
463+
def _keys_conversion(x: dict[str, Any]) -> list[str]:
464464
'''
465465
extracts object keys to a list, for cases where the values they map to are empty/irrelevant
466466
'''
@@ -471,15 +471,15 @@ def _keys_conversion(x: Dict[str, Any]) -> List[str]:
471471

472472

473473
# in case item can be either T or List[T]
474-
def _maybe_single_to_list(x: Any) -> List[Any]:
474+
def _maybe_single_to_list(x: Any) -> list[Any]:
475475
'''
476476
converts non-list objects to lists with a single item and leaves lists as-is,
477477
used to harmonize fields which avoid lists when a single value is given
478478
'''
479479
return x if isinstance(x, list) else [x]
480480

481481

482-
def _dict_dict_to_obj_list(x: Dict[str, Dict[str, Any]], identifier: str = 'identifier') -> List[Dict[str, Any]]:
482+
def _dict_dict_to_obj_list(x: dict[str, dict[str, Any]], identifier: str = 'identifier') -> list[dict[str, Any]]:
483483
'''
484484
convert e.g
485485
{'OuterKey1': {'InnerKey1': 'Value1'}, 'OuterKey2': {'InnerKey2': 'Value2'}}
@@ -497,7 +497,7 @@ def _dict_dict_to_obj_list(x: Dict[str, Dict[str, Any]], identifier: str = 'iden
497497
return out
498498

499499

500-
def _get_first(variable: List[Any]) -> Any:
500+
def _get_first(variable: list[Any]) -> Any:
501501
'''
502502
get first element from list, if the list has any; raise NoValueException otherwise
503503
'''
@@ -507,7 +507,7 @@ def _get_first(variable: List[Any]) -> Any:
507507
raise NoValueException(f'empty list passed to _get_first')
508508

509509

510-
def _get_first_fqdn(variable: List[str]) -> str:
510+
def _get_first_fqdn(variable: list[str]) -> str:
511511
'''
512512
get first valid FQDN from a list of strings
513513
'''
@@ -519,7 +519,7 @@ def _get_first_fqdn(variable: List[str]) -> str:
519519
return first
520520

521521

522-
CONVERSIONS: Dict[str, Callable[[Any], Any]] = {
522+
CONVERSIONS: dict[str, Callable[[Any], Any]] = {
523523
'ftp.features': _dict_dict_to_obj_list,
524524
'timestamp': lambda x: x + '+00',
525525
'hostnames': _get_first_fqdn,
@@ -541,7 +541,7 @@ class ShodanParserBot(ParserBot):
541541
ignore_errors = True
542542
minimal_mode = False
543543

544-
def apply_mapping(self, mapping: Dict[str, Any], data: Dict[str, Any], key_path: Tuple[str, ...] = ()) -> Dict[str, Any]:
544+
def apply_mapping(self, mapping: dict[str, Any], data: dict[str, Any], key_path: tuple[str, ...] = ()) -> dict[str, Any]:
545545
self.logger.debug(f'Applying mapping {mapping!r} to data {data!r}.')
546546
event = {}
547547
for key in data.keys() & mapping.keys():

intelmq/bots/parsers/twitter/parser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def init(self):
2020
super().init()
2121

2222
@staticmethod
23-
def check(parameters: dict) -> Optional[List[List[str]]]:
23+
def check(parameters: dict) -> Optional[list[list[str]]]:
2424
return [["warning", DEPRECATION_WARNING]]
2525

2626

intelmq/lib/bot.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ class Bot:
5656
__stats_cache: cache.Cache = None
5757
__source_pipeline = None
5858
__destination_pipeline = None
59-
__log_buffer: List[tuple] = []
59+
__log_buffer: list[tuple] = []
6060
# runtime_file
6161
__runtime_settings: Optional[dict] = None
6262
# settings provided via parameter
@@ -612,7 +612,7 @@ def __print_log_buffer(self):
612612
print(level.upper(), '-', message)
613613
self.__log_buffer = []
614614

615-
def __check_bot_id(self, name: str) -> Tuple[str, str, str]:
615+
def __check_bot_id(self, name: str) -> tuple[str, str, str]:
616616
res = re.fullmatch(r'([0-9a-zA-Z\-]+)(\.[0-9]+)?', name)
617617
if res:
618618
if not (res.group(2) and threading.current_thread() == threading.main_thread()):
@@ -975,7 +975,7 @@ def set_request_parameters(self):
975975
self.http_header['User-agent'] = self.http_user_agent
976976

977977
@staticmethod
978-
def check(parameters: dict) -> Optional[List[List[str]]]:
978+
def check(parameters: dict) -> Optional[list[list[str]]]:
979979
"""
980980
The bot's own check function can perform individual checks on it's
981981
parameters.

intelmq/lib/datatypes.py

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ def validate(value: str) -> [Callable, Optional[str]]:
113113
:return: correct time conversion function and the format string
114114
"""
115115

116-
split_value: List[str] = value.split('|')
116+
split_value: list[str] = value.split('|')
117117
conversion: Callable
118118
conversion_name: str = split_value[0]
119119
format_string: Optional[str] = split_value[1] if len(split_value) > 1 else None
@@ -139,19 +139,4 @@ def validate(value: str) -> [Callable, Optional[str]]:
139139
return conversion, format_string
140140

141141

142-
if version_info < (3, 9):
143-
class Dict39(dict):
144-
"""
145-
Python 3.9 introduced the handy | operator for dicts.
146-
For backwards-compatibility, this is the backport
147-
as IntelMQ supports Python >= 3.7
148-
"""
149-
def __or__(self, other: dict) -> 'Dict39':
150-
"""
151-
Create a new dictionary with the merged keys and values of d and other, which must both be dictionaries. The values of other take priority when d and other share keys.
152-
"""
153-
ret = Dict39(self.copy())
154-
ret.update(other)
155-
return ret
156-
else:
157-
Dict39 = dict
142+
Dict39 = dict

intelmq/lib/message.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313
import re
1414
import warnings
1515
from collections import defaultdict
16-
from typing import Any, Dict, Iterable, Optional, Sequence, Union, Tuple
16+
from typing import Any, Dict, Optional, Union, Tuple
17+
from collections.abc import Iterable, Sequence
1718
from pkg_resources import resource_filename
1819

1920
import intelmq.lib.exceptions as exceptions
@@ -332,7 +333,7 @@ def unserialize(message_string: str):
332333
message = json.loads(message_string)
333334
return message
334335

335-
def __is_valid_key(self, key: str) -> Tuple[bool, str]:
336+
def __is_valid_key(self, key: str) -> tuple[bool, str]:
336337
try:
337338
class_name, subitem = self.__get_type_config(key)
338339
except KeyError:

intelmq/lib/mixins/stomp.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ class StompMixin:
6363
# Helper methods intended to be used in subclasses
6464

6565
@classmethod
66-
def stomp_bot_parameters_check(cls, parameters: dict) -> List[List[str]]:
66+
def stomp_bot_parameters_check(cls, parameters: dict) -> list[list[str]]:
6767
"""Intended to be used in bots' `check()` static/class method."""
6868
logs = []
6969
cls.__verify_parameters(
@@ -80,7 +80,7 @@ def stomp_bot_runtime_initial_check(self) -> None:
8080
on_error=self.__raise_value_error,
8181
)
8282

83-
def prepare_stomp_connection(self) -> Tuple['stomp.Connection', dict]:
83+
def prepare_stomp_connection(self) -> tuple['stomp.Connection', dict]:
8484
"""
8585
Get a `(<STOMP connection>, <STOMP connect arguments>)` pair.
8686
@@ -178,7 +178,7 @@ def __get_own_attribute(self, param_name: str) -> Any:
178178
def __raise_value_error(self, msg: str) -> NoReturn:
179179
raise ValueError(msg)
180180

181-
def __get_ssl_and_connect_kwargs(self) -> Tuple[dict, dict]:
181+
def __get_ssl_and_connect_kwargs(self) -> tuple[dict, dict]:
182182
# Note: a *non-empty* and *non-None* `ca_certs` argument must
183183
# always be passed to `set_ssl()`; otherwise the `stomp.py`'s
184184
# machinery would *not* enable any certificate verification!
@@ -276,7 +276,7 @@ def patch_stomp_transport_ssl(cls) -> None:
276276
#
277277
# Proxying/substituting `ssl` tools for `stomp.transport` module
278278

279-
def __dir__(self) -> List[str]:
279+
def __dir__(self) -> list[str]:
280280
return dir(ssl)
281281

282282
def __getattribute__(self, name: str) -> Any:

intelmq/lib/processmanager.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
import sys
1616
import time
1717
import xmlrpc.client
18-
from typing import Union, Iterable
18+
from typing import Union
19+
from collections.abc import Iterable
1920

2021

2122
from intelmq import (DEFAULT_LOGGING_LEVEL, # noqa: F401

intelmq/lib/splitreports.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,12 +39,13 @@
3939
chunk size must take this into account, but multiplying the actual
4040
limit by 3/4 and subtracting a generous amount for the meta data.
4141
"""
42-
from typing import BinaryIO, Generator, List, Optional
42+
from typing import BinaryIO, List, Optional
43+
from collections.abc import Generator
4344

4445
from intelmq.lib.message import Report
4546

4647

47-
def split_chunks(chunk: bytes, chunk_size: int) -> List[bytes]:
48+
def split_chunks(chunk: bytes, chunk_size: int) -> list[bytes]:
4849
"""Split a bytestring into chunk_size pieces at ASCII newlines characters.
4950
5051
The return value is a list of bytestring objects. Appending all of

0 commit comments

Comments
 (0)