From eca1fe3d84c0ce1347643090f27b50a95debdadc Mon Sep 17 00:00:00 2001 From: "John T. Wodder II" Date: Thu, 28 Oct 2021 14:24:31 -0400 Subject: [PATCH] Cut down on code duplication --- dandi/dandiarchive.py | 44 ++++++++++++++----------------------------- 1 file changed, 14 insertions(+), 30 deletions(-) diff --git a/dandi/dandiarchive.py b/dandi/dandiarchive.py index e793151d3..0e1032eeb 100644 --- a/dandi/dandiarchive.py +++ b/dandi/dandiarchive.py @@ -155,15 +155,10 @@ def get_assets( self, client: DandiAPIClient, order: Optional[str] = None, strict: bool = False ) -> Iterator[BaseRemoteAsset]: """Returns all assets in the Dandiset""" - try: + with _maybe_strict(strict): yield from self.get_dandiset(client, lazy=not strict).get_assets( order=order ) - except NotFoundError: - if strict: - raise - else: - return class SingleAssetURL(ParsedDandiURL): @@ -194,13 +189,8 @@ def get_assets( a `NotFoundError` is raised if ``strict`` is true, and nothing is yielded if ``strict`` is false. """ - try: + with _maybe_strict(strict): yield client.get_asset(self.asset_id) - except NotFoundError: - if strict: - raise - else: - return def get_asset_ids(self, client: DandiAPIClient) -> Iterator[str]: """Yields the ID of the asset (regardless of whether it exists)""" @@ -222,13 +212,8 @@ def get_assets( exist, then a `NotFoundError` is raised if ``strict`` is true, and nothing is yielded if ``strict`` is false. """ - try: + with _maybe_strict(strict): yield self.get_dandiset(client, lazy=not strict).get_asset(self.asset_id) - except NotFoundError: - if strict: - raise - else: - return def get_asset_ids(self, client: DandiAPIClient) -> Iterator[str]: """Yields the ID of the asset (regardless of whether it exists)""" @@ -244,15 +229,10 @@ def get_assets( self, client: DandiAPIClient, order: Optional[str] = None, strict: bool = False ) -> Iterator[BaseRemoteAsset]: """Returns the assets whose paths start with `path`""" - try: + with _maybe_strict(strict): yield from self.get_dandiset( client, lazy=not strict ).get_assets_with_path_prefix(self.path, order=order) - except NotFoundError: - if strict: - raise - else: - return class AssetItemURL(SingleAssetURL): @@ -319,15 +299,19 @@ def get_assets( path = self.path if not path.endswith("/"): path += "/" - try: + with _maybe_strict(strict): yield from self.get_dandiset( client, lazy=not strict ).get_assets_with_path_prefix(path, order=order) - except NotFoundError: - if strict: - raise - else: - return + + +@contextmanager +def _maybe_strict(strict: bool) -> Iterator[None]: + try: + yield + except NotFoundError: + if strict: + raise @contextmanager