Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removing eval in model weight API #2323

Merged
merged 7 commits into from
Sep 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions tests/models/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,8 @@ def test_get_weight(enum: WeightsEnum) -> None:
def test_list_models() -> None:
models = [builder.__name__ for builder in builders]
assert set(models) == set(list_models())


def test_invalid_model() -> None:
with pytest.raises(ValueError, match='bad_model is not a valid WeightsEnum'):
get_weight('bad_model')
13 changes: 11 additions & 2 deletions torchgeo/models/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
'vit_small_patch16_224': vit_small_patch16_224,
}

_model_weights = {
_model_weights: dict[str | Callable[..., nn.Module], WeightsEnum] = {
dofa_base_patch16_224: DOFABase16_Weights,
dofa_large_patch16_224: DOFALarge16_Weights,
resnet18: ResNet18_Weights,
Expand Down Expand Up @@ -109,8 +109,17 @@ def get_weight(name: str) -> WeightsEnum:

Returns:
The requested weight enum.

Raises:
ValueError: If *name* is not a valid WeightsEnum.
"""
return eval(name)
for weight_name, weight_enum in _model_weights.items():
if isinstance(weight_name, str):
for sub_weight_enum in weight_enum:
if name == str(sub_weight_enum):
return sub_weight_enum

raise ValueError(f'{name} is not a valid WeightsEnum')


def list_models() -> list[str]:
Expand Down