Skip to content

Commit e3bf3d3

Browse files
authored
Add Emails class for email validation and management
1 parent 8cfff6e commit e3bf3d3

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

‎Week05/emails_sedat_celik.py‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import re
2+
3+
4+
class Emails(list):
5+
EMAIL_PATTERN = re.compile(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")
6+
7+
def __init__(self, emails=None):
8+
if emails is None:
9+
emails = []
10+
elif isinstance(emails, (str, bytes)) or not hasattr(emails, "__iter__"):
11+
raise ValueError("Input must be an iterable of email strings.")
12+
13+
unique_emails = []
14+
for email in emails:
15+
self.validate(email)
16+
if email not in unique_emails:
17+
unique_emails.append(email)
18+
19+
super().__init__(unique_emails)
20+
21+
@property
22+
def data(self):
23+
return self
24+
25+
@staticmethod
26+
def validate(email):
27+
if isinstance(email, (list, tuple, set)):
28+
for item in email:
29+
Emails.validate(item)
30+
return True
31+
32+
if not isinstance(email, str) or not Emails.EMAIL_PATTERN.match(email):
33+
raise ValueError(f"Invalid email address: {email!r}")
34+
return True
35+
36+
def append(self, email):
37+
self.validate(email)
38+
if email not in self:
39+
super().append(email)
40+
41+
def extend(self, emails):
42+
for email in emails:
43+
self.append(email)
44+
45+
def insert(self, index, email):
46+
self.validate(email)
47+
if email not in self:
48+
super().insert(index, email)
49+
50+
def __repr__(self):
51+
return f"{self.__class__.__name__}({super().__repr__()})"
52+
53+
def __str__(self):
54+
return ", ".join(self)

0 commit comments

Comments
 (0)