Skip to content

Commit

Permalink
Merge pull request #3234 from ff137/art/fix-bad-unreachable-code-warning
Browse files Browse the repository at this point in the history
🎨 fix type hints for optional method parameters
  • Loading branch information
dbluhm authored Sep 16, 2024
2 parents e8c07b5 + f1b7708 commit 17e9f16
Show file tree
Hide file tree
Showing 226 changed files with 1,421 additions and 1,195 deletions.
8 changes: 5 additions & 3 deletions aries_cloudagent/admin/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,8 +224,8 @@ def __init__(
outbound_message_router: Coroutine,
webhook_router: Callable,
conductor_stop: Coroutine,
task_queue: TaskQueue = None,
conductor_stats: Coroutine = None,
task_queue: Optional[TaskQueue] = None,
conductor_stats: Optional[Coroutine] = None,
):
"""Initialize an AdminServer instance.
Expand Down Expand Up @@ -652,7 +652,9 @@ async def _on_record_event(self, profile: Profile, event: Event):
if webhook_topic:
await self.send_webhook(profile, webhook_topic, event.payload)

async def send_webhook(self, profile: Profile, topic: str, payload: dict = None):
async def send_webhook(
self, profile: Profile, topic: str, payload: Optional[dict] = None
):
"""Add a webhook to the queue, to send to all registered targets."""
wallet_id = profile.settings.get("wallet.id")
webhook_urls = profile.settings.get("admin.webhook_urls")
Expand Down
3 changes: 2 additions & 1 deletion aries_cloudagent/admin/tests/test_admin_server.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import gc
import json
from typing import Optional
from unittest import IsolatedAsyncioTestCase

import pytest
Expand Down Expand Up @@ -108,7 +109,7 @@ async def test_ready_middleware(self):
await test_module.ready_middleware(request, handler)

def get_admin_server(
self, settings: dict = None, context: InjectionContext = None
self, settings: Optional[dict] = None, context: Optional[InjectionContext] = None
) -> AdminServer:
if not context:
context = InjectionContext()
Expand Down
2 changes: 1 addition & 1 deletion aries_cloudagent/anoncreds/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def __init__(
self,
message: str,
obj_id: str,
obj: T = None,
obj: Optional[T] = None,
*args,
**kwargs,
):
Expand Down
8 changes: 4 additions & 4 deletions aries_cloudagent/anoncreds/default/legacy_indy/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -805,7 +805,7 @@ async def _revoc_reg_entry_with_fix(
rev_reg_def_type: str,
entry: dict,
write_ledger: bool,
endorser_did: str = None,
endorser_did: Optional[str] = None,
) -> dict:
"""Send a revocation registry entry to the ledger with fixes if needed."""
multitenant_mgr = profile.inject_or(BaseMultitenantManager)
Expand Down Expand Up @@ -1078,7 +1078,7 @@ async def fix_ledger_entry(
apply_ledger_update: bool,
genesis_transactions: str,
write_ledger: bool = True,
endorser_did: str = None,
endorser_did: Optional[str] = None,
) -> Tuple[dict, dict, dict]:
"""Fix the ledger entry to match wallet-recorded credentials."""

Expand Down Expand Up @@ -1209,8 +1209,8 @@ async def txn_submit(
self,
ledger: BaseLedger,
ledger_transaction: str,
sign: bool = None,
taa_accept: bool = None,
sign: Optional[bool] = None,
taa_accept: Optional[bool] = None,
sign_did: DIDInfo = sentinel,
write_ledger: bool = True,
) -> str:
Expand Down
29 changes: 16 additions & 13 deletions aries_cloudagent/anoncreds/holder.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,9 +178,9 @@ async def store_credential(
credential_definition: dict,
credential_data: dict,
credential_request_metadata: dict,
credential_attr_mime_types: dict = None,
credential_id: str = None,
rev_reg_def: dict = None,
credential_attr_mime_types: Optional[dict] = None,
credential_id: Optional[str] = None,
rev_reg_def: Optional[dict] = None,
) -> str:
"""Store a credential in the wallet.
Expand Down Expand Up @@ -226,9 +226,9 @@ async def _finish_store_credential(
credential_definition: dict,
cred_recvd: Credential,
credential_request_metadata: dict,
credential_attr_mime_types: dict = None,
credential_id: str = None,
rev_reg_def: dict = None,
credential_attr_mime_types: Optional[dict] = None,
credential_id: Optional[str] = None,
rev_reg_def: Optional[dict] = None,
) -> str:
credential_data = cred_recvd.to_dict()
schema_id = cred_recvd.schema_id
Expand Down Expand Up @@ -288,9 +288,9 @@ async def store_credential_w3c(
credential_definition: dict,
credential_data: dict,
credential_request_metadata: dict,
credential_attr_mime_types: dict = None,
credential_id: str = None,
rev_reg_def: dict = None,
credential_attr_mime_types: Optional[dict] = None,
credential_id: Optional[str] = None,
rev_reg_def: Optional[dict] = None,
) -> str:
"""Store a credential in the wallet.
Expand Down Expand Up @@ -515,7 +515,10 @@ async def _get_credential(self, credential_id: str) -> Credential:
raise AnonCredsHolderError("Error loading requested credential") from err

async def credential_revoked(
self, credential_id: str, timestamp_from: int = None, timestamp_to: int = None
self,
credential_id: str,
timestamp_from: Optional[int] = None,
timestamp_to: Optional[int] = None,
) -> bool:
"""Check ledger for revocation status of credential by credential id.
Expand Down Expand Up @@ -565,7 +568,7 @@ async def delete_credential(self, credential_id: str):
) from err # noqa: E501

async def get_mime_type(
self, credential_id: str, attr: str = None
self, credential_id: str, attr: Optional[str] = None
) -> Union[dict, str]:
"""Get MIME type per attribute (or for all attributes).
Expand Down Expand Up @@ -595,7 +598,7 @@ async def create_presentation(
requested_credentials: dict,
schemas: Dict[str, AnonCredsSchema],
credential_definitions: Dict[str, CredDef],
rev_states: dict = None,
rev_states: Optional[dict] = None,
) -> str:
"""Get credentials stored in the wallet.
Expand Down Expand Up @@ -686,7 +689,7 @@ async def create_presentation_w3c(
credentials_w3c_metadata: list,
schemas: Dict[str, AnonCredsSchema],
credential_definitions: Dict[str, CredDef],
rev_states: dict = None,
rev_states: Optional[dict] = None,
) -> dict:
"""Get credentials stored in the wallet.
Expand Down
3 changes: 2 additions & 1 deletion aries_cloudagent/anoncreds/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from os.path import isdir, join
from pathlib import Path
from platform import system
from typing import Optional

from aiohttp import web

Expand All @@ -16,7 +17,7 @@ async def generate_pr_nonce() -> str:
return str(int.from_bytes(urandom(10), "big"))


def indy_client_dir(subpath: str = None, create: bool = False) -> str:
def indy_client_dir(subpath: Optional[str] = None, create: bool = False) -> str:
"""Return '/'-terminated subdirectory of indy-client directory.
Args:
Expand Down
24 changes: 12 additions & 12 deletions aries_cloudagent/askar/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import asyncio
import logging
import time
from typing import Any, Mapping
from typing import Any, Mapping, Optional
from weakref import ref

from aries_askar import AskarError, Session, Store
Expand Down Expand Up @@ -37,14 +37,14 @@ class AskarProfile(Profile):
def __init__(
self,
opened: AskarOpenStore,
context: InjectionContext = None,
context: Optional[InjectionContext] = None,
*,
profile_id: str = None,
profile_id: Optional[str] = None,
):
"""Create a new AskarProfile instance."""
super().__init__(context=context, name=opened.name, created=opened.created)
self.opened = opened
self.ledger_pool: IndyVdrLedgerPool = None
self.ledger_pool: Optional[IndyVdrLedgerPool] = None
self.profile_id = profile_id
self.init_ledger_pool()
self.bind_providers()
Expand Down Expand Up @@ -178,11 +178,11 @@ def bind_providers(self):
),
)

def session(self, context: InjectionContext = None) -> ProfileSession:
def session(self, context: Optional[InjectionContext] = None) -> ProfileSession:
"""Start a new interactive session with no transaction support requested."""
return AskarProfileSession(self, False, context=context)

def transaction(self, context: InjectionContext = None) -> ProfileSession:
def transaction(self, context: Optional[InjectionContext] = None) -> ProfileSession:
"""Start a new interactive session with commit and rollback support.
If the current backend does not support transactions, then commit
Expand All @@ -205,7 +205,7 @@ def __init__(
profile: AskarProfile,
is_txn: bool,
*,
context: InjectionContext = None,
context: Optional[InjectionContext] = None,
settings: Mapping[str, Any] = None,
):
"""Create a new IndySdkProfileSession instance."""
Expand All @@ -215,9 +215,9 @@ def __init__(
else:
self._opener = self.profile.store.session(profile.profile_id)
self._profile = profile
self._handle: Session = None
self._acquire_start: float = None
self._acquire_end: float = None
self._handle: Optional[Session] = None
self._acquire_start: Optional[float] = None
self._acquire_end: Optional[float] = None

@property
def handle(self) -> Session:
Expand Down Expand Up @@ -288,7 +288,7 @@ async def _setup(self):
),
)

async def _teardown(self, commit: bool = None):
async def _teardown(self, commit: Optional[bool] = None):
"""Dispose of the session or transaction connection."""
if commit:
try:
Expand Down Expand Up @@ -338,6 +338,6 @@ async def open(
return AskarProfile(opened, context)

@classmethod
async def generate_store_key(self, seed: str = None) -> str:
async def generate_store_key(self, seed: Optional[str] = None) -> str:
"""Generate a raw store key."""
return Store.generate_raw_key(validate_seed(seed))
26 changes: 14 additions & 12 deletions aries_cloudagent/askar/profile_anon.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import asyncio
import logging
import time
from typing import Any, Mapping
from typing import Any, Mapping, Optional
from weakref import ref

from aries_askar import AskarError, Session, Store
Expand Down Expand Up @@ -39,14 +39,14 @@ class AskarAnoncredsProfile(Profile):
def __init__(
self,
opened: AskarOpenStore,
context: InjectionContext = None,
context: Optional[InjectionContext] = None,
*,
profile_id: str = None,
profile_id: Optional[str] = None,
):
"""Create a new AskarProfile instance."""
super().__init__(context=context, name=opened.name, created=opened.created)
self.opened = opened
self.ledger_pool: IndyVdrLedgerPool = None
self.ledger_pool: Optional[IndyVdrLedgerPool] = None
self.profile_id = profile_id
self.init_ledger_pool()
self.bind_providers()
Expand Down Expand Up @@ -159,12 +159,14 @@ def bind_providers(self):
BaseLedger, ClassProvider(IndyVdrLedger, self.ledger_pool, ref(self))
)

def session(self, context: InjectionContext = None) -> "AskarAnoncredsProfileSession":
def session(
self, context: Optional[InjectionContext] = None
) -> "AskarAnoncredsProfileSession":
"""Start a new interactive session with no transaction support requested."""
return AskarAnoncredsProfileSession(self, False, context=context)

def transaction(
self, context: InjectionContext = None
self, context: Optional[InjectionContext] = None
) -> "AskarAnoncredsProfileSession":
"""Start a new interactive session with commit and rollback support.
Expand All @@ -188,7 +190,7 @@ def __init__(
profile: AskarAnoncredsProfile,
is_txn: bool,
*,
context: InjectionContext = None,
context: Optional[InjectionContext] = None,
settings: Mapping[str, Any] = None,
):
"""Create a new AskarAnoncredsProfileSession instance."""
Expand All @@ -198,9 +200,9 @@ def __init__(
else:
self._opener = self.profile.store.session(profile.profile_id)
self._profile = profile
self._handle: Session = None
self._acquire_start: float = None
self._acquire_end: float = None
self._handle: Optional[Session] = None
self._acquire_start: Optional[float] = None
self._acquire_end: Optional[float] = None

@property
def handle(self) -> Session:
Expand Down Expand Up @@ -239,7 +241,7 @@ async def _setup(self):
ClassProvider("aries_cloudagent.storage.askar.AskarStorage", ref(self)),
)

async def _teardown(self, commit: bool = None):
async def _teardown(self, commit: Optional[bool] = None):
"""Dispose of the session or transaction connection."""
if commit:
try:
Expand Down Expand Up @@ -289,6 +291,6 @@ async def open(
return AskarAnoncredsProfile(opened, context)

@classmethod
async def generate_store_key(self, seed: str = None) -> str:
async def generate_store_key(self, seed: Optional[str] = None) -> str:
"""Generate a raw store key."""
return Store.generate_raw_key(validate_seed(seed))
3 changes: 2 additions & 1 deletion aries_cloudagent/askar/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import json
import logging
import urllib
from typing import Optional

from aries_askar import AskarError, AskarErrorCode, Store

Expand All @@ -24,7 +25,7 @@ class AskarStoreConfig:
KEY_DERIVATION_ARGON2I_INT = "kdf:argon2i:int"
KEY_DERIVATION_ARGON2I_MOD = "kdf:argon2i:mod"

def __init__(self, config: dict = None):
def __init__(self, config: Optional[dict] = None):
"""Initialize a `AskarWallet` instance.
Args:
Expand Down
2 changes: 1 addition & 1 deletion aries_cloudagent/cache/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ class CacheKeyLock:
def __init__(self, cache: BaseCache, key: Text):
"""Initialize the key lock."""
self.cache = cache
self.exception: BaseException = None
self.exception: Optional[BaseException] = None
self.key = key
self.released = False
self._future: asyncio.Future = asyncio.get_event_loop().create_future()
Expand Down
6 changes: 4 additions & 2 deletions aries_cloudagent/cache/in_memory.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Basic in-memory cache implementation."""

import time
from typing import Any, Sequence, Text, Union
from typing import Any, Optional, Sequence, Text, Union

from .base import BaseCache

Expand Down Expand Up @@ -38,7 +38,9 @@ async def get(self, key: Text):
self._remove_expired_cache_items()
return self._cache.get(key)["value"] if self._cache.get(key) else None

async def set(self, keys: Union[Text, Sequence[Text]], value: Any, ttl: int = None):
async def set(
self, keys: Union[Text, Sequence[Text]], value: Any, ttl: Optional[int] = None
):
"""Add an item to the cache with an optional ttl.
Overwrites existing cache entries.
Expand Down
2 changes: 1 addition & 1 deletion aries_cloudagent/commands/upgrade.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class UpgradeError(BaseError):
class VersionUpgradeConfig:
"""Handle ACA-Py version upgrade config."""

def __init__(self, config_path: str = None):
def __init__(self, config_path: Optional[str] = None):
"""Initialize config for use during upgrade process."""
self.function_map_config = UPGRADE_EXISTING_RECORDS_FUNCTION_MAPPING
self.upgrade_configs = {}
Expand Down
Loading

0 comments on commit 17e9f16

Please sign in to comment.