Skip to content

Commit 045c11b

Browse files
authored
Add Emails class for email validation and storage
1 parent 71f5b39 commit 045c11b

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Week05/emails_elifsude_yilmaz.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import re
2+
3+
4+
class Emails(list):
5+
def __init__(self, data):
6+
self.data = []
7+
self.validate(data)
8+
super().__init__(self.data)
9+
10+
def validate(self, data):
11+
# only list input
12+
if not isinstance(data, list):
13+
raise ValueError("Input must be a list")
14+
15+
email_pattern = re.compile(
16+
r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$"
17+
)
18+
19+
seen = set()
20+
21+
for item in data:
22+
# allow only strings
23+
if not isinstance(item, str):
24+
raise ValueError("All emails must be strings")
25+
26+
# valid email check
27+
if not email_pattern.match(item):
28+
raise ValueError("Invalid email address")
29+
30+
# remove duplicates
31+
if item not in seen:
32+
seen.add(item)
33+
self.data.append(item)
34+
35+
def __repr__(self):
36+
return f"Emails({self.data})"
37+
38+
def __str__(self):
39+
return ", ".join(self.data)

0 commit comments

Comments
 (0)