Skip to content

Commit

Permalink
Add pyupgrade with --py310-plus in pre-commit (jointakahe#103)
Browse files Browse the repository at this point in the history
  • Loading branch information
pauloxnet authored Dec 5, 2022
1 parent dd8e823 commit a9bb4a7
Show file tree
Hide file tree
Showing 20 changed files with 89 additions and 91 deletions.
6 changes: 6 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ repos:
- id: pretty-format-json
- id: trailing-whitespace

- repo: https://github.com/asottile/pyupgrade
rev: "v3.3.0"
hooks:
- id: pyupgrade
args: [--py310-plus]

- repo: https://github.com/psf/black
rev: 22.10.0
hooks:
Expand Down
7 changes: 3 additions & 4 deletions activities/models/hashtag.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import re
from datetime import date, timedelta
from typing import Dict, List

import urlman
from asgiref.sync import sync_to_async
Expand Down Expand Up @@ -138,7 +137,7 @@ def display_name(self):
def __str__(self):
return self.display_name

def usage_months(self, num: int = 12) -> Dict[date, int]:
def usage_months(self, num: int = 12) -> dict[date, int]:
"""
Return the most recent num months of stats
"""
Expand All @@ -153,7 +152,7 @@ def usage_months(self, num: int = 12) -> Dict[date, int]:
results[date(year, month, 1)] = val
return dict(sorted(results.items(), reverse=True)[:num])

def usage_days(self, num: int = 7) -> Dict[date, int]:
def usage_days(self, num: int = 7) -> dict[date, int]:
"""
Return the most recent num days of stats
"""
Expand All @@ -170,7 +169,7 @@ def usage_days(self, num: int = 7) -> Dict[date, int]:
return dict(sorted(results.items(), reverse=True)[:num])

@classmethod
def hashtags_from_content(cls, content) -> List[str]:
def hashtags_from_content(cls, content) -> list[str]:
"""
Return a parsed and sanitized of hashtags found in content without
leading '#'.
Expand Down
15 changes: 8 additions & 7 deletions activities/models/post.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import re
from typing import Dict, Iterable, List, Optional, Set
from collections.abc import Iterable
from typing import Optional

import httpx
import urlman
Expand Down Expand Up @@ -324,10 +325,10 @@ def create_local(
cls,
author: Identity,
content: str,
summary: Optional[str] = None,
summary: str | None = None,
visibility: int = Visibilities.public,
reply_to: Optional["Post"] = None,
attachments: Optional[List] = None,
attachments: list | None = None,
) -> "Post":
with transaction.atomic():
# Find mentions in this post
Expand Down Expand Up @@ -363,9 +364,9 @@ def create_local(
def edit_local(
self,
content: str,
summary: Optional[str] = None,
summary: str | None = None,
visibility: int = Visibilities.public,
attachments: Optional[List] = None,
attachments: list | None = None,
):
with transaction.atomic():
# Strip all HTML and apply linebreaks filter
Expand All @@ -380,7 +381,7 @@ def edit_local(
self.save()

@classmethod
def mentions_from_content(cls, content, author) -> Set[Identity]:
def mentions_from_content(cls, content, author) -> set[Identity]:
mention_hits = cls.mention_regex.findall(content)
mentions = set()
for precursor, handle in mention_hits:
Expand Down Expand Up @@ -413,7 +414,7 @@ async def ensure_hashtags(self) -> None:

### ActivityPub (outbound) ###

def to_ap(self) -> Dict:
def to_ap(self) -> dict:
"""
Returns the AP JSON for this object
"""
Expand Down
6 changes: 2 additions & 4 deletions activities/models/post_interaction.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Dict

from django.db import models, transaction
from django.utils import timezone

Expand Down Expand Up @@ -195,7 +193,7 @@ async def afetch_full(self):

### ActivityPub (outbound) ###

def to_ap(self) -> Dict:
def to_ap(self) -> dict:
"""
Returns the AP JSON for this object
"""
Expand Down Expand Up @@ -223,7 +221,7 @@ def to_ap(self) -> Dict:
raise ValueError("Cannot turn into AP")
return value

def to_undo_ap(self) -> Dict:
def to_undo_ap(self) -> dict:
"""
Returns the AP JSON to undo this object
"""
Expand Down
6 changes: 2 additions & 4 deletions activities/views/search.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Set

import httpx
from asgiref.sync import async_to_sync
from django import forms
Expand Down Expand Up @@ -32,7 +30,7 @@ def search_identities_handle(self, query: str):

# Try to fetch the user by handle
query = query.lstrip("@")
results: Set[Identity] = set()
results: set[Identity] = set()
if "@" in query:
username, domain = query.split("@", 1)

Expand Down Expand Up @@ -118,7 +116,7 @@ def search_hashtags(self, query: str):
if "@" in query or "://" in query:
return set()

results: Set[Hashtag] = set()
results: set[Hashtag] = set()
query = query.lstrip("#")
for hashtag in Hashtag.objects.public().hashtag_or_alias(query)[:10]:
results.add(hashtag)
Expand Down
5 changes: 1 addition & 4 deletions core/htmx.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
from typing import Optional


class HTMXMixin:
template_name_htmx: Optional[str] = None
template_name_htmx: str | None = None

def get_template_name(self):
if self.request.htmx and self.template_name_htmx:
Expand Down
9 changes: 4 additions & 5 deletions core/ld.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import datetime
import os
import urllib.parse as urllib_parse
from typing import Dict, List, Optional, Union

from pyld import jsonld
from pyld.jsonld import JsonLdError
Expand Down Expand Up @@ -396,7 +395,7 @@ def builtin_document_loader(url: str, options={}):
)


def canonicalise(json_data: Dict, include_security: bool = False) -> Dict:
def canonicalise(json_data: dict, include_security: bool = False) -> dict:
"""
Given an ActivityPub JSON-LD document, round-trips it through the LD
systems to end up in a canonicalised, compacted format.
Expand All @@ -408,7 +407,7 @@ def canonicalise(json_data: Dict, include_security: bool = False) -> Dict:
"""
if not isinstance(json_data, dict):
raise ValueError("Pass decoded JSON data into LDDocument")
context: Union[str, List[str]]
context: str | list[str]
if include_security:
context = [
"https://www.w3.org/ns/activitystreams",
Expand All @@ -422,7 +421,7 @@ def canonicalise(json_data: Dict, include_security: bool = False) -> Dict:
return jsonld.compact(jsonld.expand(json_data), context)


def get_list(container, key) -> List:
def get_list(container, key) -> list:
"""
Given a JSON-LD value (that can be either a list, or a dict if it's just
one item), always returns a list"""
Expand All @@ -438,7 +437,7 @@ def format_ld_date(value: datetime.datetime) -> str:
return value.strftime(DATETIME_FORMAT)


def parse_ld_date(value: Optional[str]) -> Optional[datetime.datetime]:
def parse_ld_date(value: str | None) -> datetime.datetime | None:
if value is None:
return None
try:
Expand Down
18 changes: 9 additions & 9 deletions core/signatures.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import base64
import json
from typing import Dict, List, Literal, Optional, Tuple, TypedDict
from typing import Literal, TypedDict
from urllib.parse import urlparse

import httpx
Expand Down Expand Up @@ -35,7 +35,7 @@ class VerificationFormatError(VerificationError):

class RsaKeys:
@classmethod
def generate_keypair(cls) -> Tuple[str, str]:
def generate_keypair(cls) -> tuple[str, str]:
"""
Generates a new RSA keypair
"""
Expand Down Expand Up @@ -77,7 +77,7 @@ def calculate_digest(cls, data, algorithm="sha-256") -> str:
raise ValueError(f"Unknown digest algorithm {algorithm}")

@classmethod
def headers_from_request(cls, request: HttpRequest, header_names: List[str]) -> str:
def headers_from_request(cls, request: HttpRequest, header_names: list[str]) -> str:
"""
Creates the to-be-signed header payload from a Django request
"""
Expand Down Expand Up @@ -170,7 +170,7 @@ def verify_request(cls, request, public_key, skip_date=False):
async def signed_request(
cls,
uri: str,
body: Optional[Dict],
body: dict | None,
private_key: str,
key_id: str,
content_type: str = "application/json",
Expand Down Expand Up @@ -239,7 +239,7 @@ async def signed_request(

class HttpSignatureDetails(TypedDict):
algorithm: str
headers: List[str]
headers: list[str]
signature: bytes
keyid: str

Expand All @@ -250,7 +250,7 @@ class LDSignature:
"""

@classmethod
def verify_signature(cls, document: Dict, public_key: str) -> None:
def verify_signature(cls, document: dict, public_key: str) -> None:
"""
Verifies a document
"""
Expand Down Expand Up @@ -285,13 +285,13 @@ def verify_signature(cls, document: Dict, public_key: str) -> None:

@classmethod
def create_signature(
cls, document: Dict, private_key: str, key_id: str
) -> Dict[str, str]:
cls, document: dict, private_key: str, key_id: str
) -> dict[str, str]:
"""
Creates the signature for a document
"""
# Create the options document
options: Dict[str, str] = {
options: dict[str, str] = {
"@context": "https://w3id.org/identity/v1",
"creator": key_id,
"created": format_ld_date(timezone.now()),
Expand Down
23 changes: 12 additions & 11 deletions stator/graph.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import Any, Callable, ClassVar, Dict, List, Optional, Set, Tuple, Type
from collections.abc import Callable
from typing import Any, ClassVar


class StateGraph:
Expand All @@ -7,11 +8,11 @@ class StateGraph:
Does not support subclasses of existing graphs yet.
"""

states: ClassVar[Dict[str, "State"]]
choices: ClassVar[List[Tuple[object, str]]]
states: ClassVar[dict[str, "State"]]
choices: ClassVar[list[tuple[object, str]]]
initial_state: ClassVar["State"]
terminal_states: ClassVar[Set["State"]]
automatic_states: ClassVar[Set["State"]]
terminal_states: ClassVar[set["State"]]
automatic_states: ClassVar[set["State"]]

def __init_subclass__(cls) -> None:
# Collect state members
Expand Down Expand Up @@ -84,8 +85,8 @@ class State:

def __init__(
self,
try_interval: Optional[float] = None,
handler_name: Optional[str] = None,
try_interval: float | None = None,
handler_name: str | None = None,
externally_progressed: bool = False,
attempt_immediately: bool = True,
force_initial: bool = False,
Expand All @@ -95,10 +96,10 @@ def __init__(
self.externally_progressed = externally_progressed
self.attempt_immediately = attempt_immediately
self.force_initial = force_initial
self.parents: Set["State"] = set()
self.children: Set["State"] = set()
self.parents: set["State"] = set()
self.children: set["State"] = set()

def _add_to_graph(self, graph: Type[StateGraph], name: str):
def _add_to_graph(self, graph: type[StateGraph], name: str):
self.graph = graph
self.name = name
self.graph.states[name] = self
Expand Down Expand Up @@ -132,7 +133,7 @@ def terminal(self):
return not self.children

@property
def handler(self) -> Callable[[Any], Optional[str]]:
def handler(self) -> Callable[[Any], str | None]:
# Retrieve it by name off the graph
if self.handler_name is None:
raise AttributeError("No handler defined")
Expand Down
6 changes: 3 additions & 3 deletions stator/management/commands/runstator.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import List, Type, cast
from typing import cast

from asgiref.sync import async_to_sync
from django.apps import apps
Expand Down Expand Up @@ -44,7 +44,7 @@ def add_arguments(self, parser):

def handle(
self,
model_labels: List[str],
model_labels: list[str],
concurrency: int,
liveness_file: str,
schedule_interval: int,
Expand All @@ -56,7 +56,7 @@ def handle(
Config.system = Config.load_system()
# Resolve the models list into names
models = cast(
List[Type[StatorModel]],
list[type[StatorModel]],
[apps.get_model(label) for label in model_labels],
)
if not models:
Expand Down
Loading

0 comments on commit a9bb4a7

Please sign in to comment.