Skip to content

Commit

Permalink
Replace hasattr with getattr in pytorch/opacus/opacus/data_loader.py
Browse files Browse the repository at this point in the history
Summary:
The pattern
```
X.Y if hasattr(X, "Y") else Z
```
can be replaced with
```
getattr(X, "Y", Z)
```

The [getattr](https://www.w3schools.com/python/ref_func_getattr.asp) function gives more succinct code than the [hasattr](https://www.w3schools.com/python/ref_func_hasattr.asp) function. Please use it when appropriate.

**This diff is very low risk. Green tests indicate that you can safely Accept & Ship.**

Differential Revision: D44886833

fbshipit-source-id: 1e5b91a1aaace39425468b0c777fb03e59a6ec28
  • Loading branch information
r-barnes authored and facebook-github-bot committed Apr 14, 2023
1 parent 93dd307 commit fc3fd6b
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions opacus/data_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def shape_safe(x: Any) -> Tuple:
Returns:
``x.shape`` if attribute exists, empty tuple otherwise
"""
return x.shape if hasattr(x, "shape") else ()
return getattr(x, "shape", ())


def dtype_safe(x: Any) -> Union[torch.dtype, Type]:
Expand All @@ -83,7 +83,7 @@ def dtype_safe(x: Any) -> Union[torch.dtype, Type]:
Returns:
``x.dtype`` if attribute exists, type of x otherwise
"""
return x.dtype if hasattr(x, "dtype") else type(x)
return getattr(x, "dtype", type(x))


class DPDataLoader(DataLoader):
Expand Down

0 comments on commit fc3fd6b

Please sign in to comment.