Skip to content

Commit 4523407

Browse files
authored
Add Emails class for email validation and storage
Created a class to validate and store unique email addresses.
1 parent d717c64 commit 4523407

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

‎Week05/emails_darya_leven.py‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import re
2+
3+
4+
# Class to store unique and valid email addresses
5+
class Emails(list):
6+
def __init__(self, emails):
7+
# Validate emails and save them
8+
valid = self.validate(emails)
9+
super().__init__(valid)
10+
self.data = valid
11+
12+
def validate(self, emails):
13+
clean_list = []
14+
pattern = r"^[\w.+-]+@[\w-]+\.[\w.-]+$"
15+
16+
for item in emails:
17+
# Check if item is a string
18+
if not isinstance(item, str):
19+
raise ValueError("Email must be a string")
20+
# Check if email format is valid
21+
if not re.match(pattern, item):
22+
raise ValueError("Invalid email address")
23+
# Add only unique emails
24+
if item not in clean_list:
25+
clean_list.append(item)
26+
27+
return clean_list
28+
29+
def __repr__(self):
30+
# Return code representation of the object
31+
return f"Emails({list(self)})"
32+
33+
def __str__(self):
34+
# Return readable string of emails
35+
return "\n".join(self)

0 commit comments

Comments
 (0)