There's more...

You may find the complete implementation of our Contact class quite verbose and repetitive. For each attribute, we will need to assign it in the __init__ method and write its corresponding getter and setter methods.

Fortunately, we have several alternatives to reduce this amount of boilerplate code. The namedtuple function from the standard library allows us to create lightweight tuple subclasses with named fields:

from collections import namedtuple

Contact = namedtuple("Contact", ["last_name", "first_name",
"email", "phone"])

However, we still need to add a workaround to implement the validation of the fields. To address this common problem, we can use the attrs package available from the Python Package Index. 

As usual, you can install it using the following command line with pip:

$ pip install attrs

Once installed, you can replace all the properties with the attr.ib descriptor. It also lets you specify a validator callback that takes the class instance, the attribute to be modified, and the value to be set.

With some minor modifications, we can rewrite our Contact class, reducing the number of lines of code by half:

import re
import attr

def required(message):
def func(self, attr, val):
if not val: raise ValueError(message)
return func

def match(pattern, message):
regex = re.compile(pattern)
def func(self, attr, val):
if val and not regex.match(val):
raise ValueError(message)
return func

@attr.s
class Contact(object):
last_name = attr.ib(validator=required("Last name is required"))
first_name = attr.ib(validator=required("First name is required"))
email = attr.ib(validator=match(r"[^@]+@[^@]+.[^@]+",
"Invalid email format"))
phone = attr.ib(validator=match(r"([0-9]{3})s[0-9]{7}",
"Invalid phone format"))

When adding an external dependency in your projects, note not only the productivity benefits, but also other important aspects, such as documentation, support, and licensing.

You can find more information about the attrs package on its website at http://www.attrs.org/en/stable/.

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

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