Skip to content

Commit

Permalink
feat: Make SecretStr hashable (#4399)
Browse files Browse the repository at this point in the history
* feat: Make SecretStr hashable

* docs: Add change documentation

* test: Assert that the hash of SecretStr is an integer value

Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com>

* feat: Make SecretBytes hashable

Co-authored-by: Johannes Rueschel <johannes.rueschel@telekom.de>
Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com>
  • Loading branch information
3 people committed Aug 19, 2022
1 parent 899b5f0 commit ba58f94
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 0 deletions.
1 change: 1 addition & 0 deletions changes/4387-chbndrhnns.md
@@ -0,0 +1 @@
Make `SecretStr` and `SecretBytes` hashable
3 changes: 3 additions & 0 deletions pydantic/types.py
Expand Up @@ -834,6 +834,9 @@ def __eq__(self, other: Any) -> bool:
def __str__(self) -> str:
return '**********' if self.get_secret_value() else ''

def __hash__(self) -> int:
return hash(self.get_secret_value())

@abc.abstractmethod
def get_secret_value(self) -> Any: # pragma: no cover
...
Expand Down
8 changes: 8 additions & 0 deletions tests/test_types.py
Expand Up @@ -2663,6 +2663,10 @@ class Foobar(BaseModel):
assert m.password.get_secret_value() == '1234'


def test_secretstr_is_hashable():
assert type(hash(SecretStr('secret'))) is int


def test_secretstr_error():
class Foobar(BaseModel):
password: SecretStr
Expand Down Expand Up @@ -2755,6 +2759,10 @@ class Foobar(BaseModel):
_ = Foobar(password=SecretBytes(b'1234'))


def test_secretbytes_is_hashable():
assert type(hash(SecretBytes(b'secret'))) is int


def test_secretbytes_error():
class Foobar(BaseModel):
password: SecretBytes
Expand Down

0 comments on commit ba58f94

Please sign in to comment.