Skip to content

Commit

Permalink
Move __hash__ to BaseAWSObject to support objects in dictionaries (Fixes
Browse files Browse the repository at this point in the history
 #2204)

PR #2182 added support for troposphere object comparison. Upon release
there was an issue (#2196) where Parameter was not hashable and fixed in
PR #2200. This fix was a minimal one just for Parameter but PR #2204
showed use cases for the base object to be hashable as well.
  • Loading branch information
markpeek committed Nov 10, 2023
1 parent 6f4f68e commit 68f07e5
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
11 changes: 11 additions & 0 deletions tests/test_basic.py
Expand Up @@ -122,6 +122,17 @@ def test___ne__(self):
assert Parameter("param1") != Parameter("param2")
assert Stack("stack1") != Stack("stack2")

def test___hash__(self):
"""Test __hash__."""
from troposphere.ec2 import SecurityGroup

test_sg = SecurityGroup(
"TestSg",
VpcId="myVPC",
GroupDescription="Test Security Group",
)
_ = hash(test_sg)

def test_badproperty(self):
with self.assertRaises(AttributeError):
Instance(
Expand Down
6 changes: 3 additions & 3 deletions troposphere/__init__.py
Expand Up @@ -431,6 +431,9 @@ def __eq__(self, other: object) -> bool:
def __ne__(self, other: object) -> bool:
return not self == other

def __hash__(self) -> int:
return hash(json.dumps({"title": self.title, **self.to_dict()}, indent=0))


class AWSObject(BaseAWSObject):
dictname = "Properties"
Expand Down Expand Up @@ -1115,6 +1118,3 @@ def check_type(t: type, v: Any) -> bool:
"%s can only be used with parameters of "
"the CommaDelimitedList type." % p
)

def __hash__(self) -> int:
return hash(json.dumps({"title": self.title, **self.to_dict()}, indent=0))

0 comments on commit 68f07e5

Please sign in to comment.