How to do it...

First, we define a couple of utility functions that we will reuse to validate the fields that are mandatory or must follow a specific format:

def required(value, message):
if not value:
raise ValueError(message)
return value

def matches(value, regex, message):
if value and not regex.match(value):
raise ValueError(message)
return value

Then, we define our Contact class and its __init__ method. We set here all the parameters to the corresponding fields. We also store the compiled regular expressions as class attributes since we will use them for every instance to perform the field validations:

import re

class Contact(object):
email_regex = re.compile(r"[^@]+@[^@]+.[^@]+")
phone_regex = re.compile(r"([0-9]{3})s[0-9]{7}")

def __init__(self, last_name, first_name, email, phone):
self.last_name = last_name
self.first_name = first_name
self.email = email
self.phone = phone

However, this definition is not enough to enforce the validations for each field. To do so, we use the @property decorator, which allow us to wrap access to an internal attribute:

    @property
def last_name(self):
return self._last_name

@last_name.setter
def last_name(self, value):
self._last_name = required(value, "Last name is required")

The same technique is applied for first_name since it is also mandatory. The email and phone attributes follow a similar approach, using the matches function with the corresponding regular expression:

    @property
def email(self):
return self._email

@email.setter
def email(self, value):
self._email = matches(value, self.email_regex,
"Invalid email format")

This script should be saved as chapter5_01.py, since we will import it later in future recipes with this name. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset