Hello Python folks! I am excited to start this python recipes book to the delight of python lovers, where I'll be sharing my thoughts and experiences with all of you.
The First recipe is all about combining multiple Python features in just a few lines of code.
So, lets’ start:
- User emails class - Class that holds all users' email addresses
- Set object – A Set is an unordered collection of unique elements
- @classmethod decorator – Alternative constructor (no need for__init__)
- Generator expression – that allows us to iterate over large dataset lazily, efficiently and with minimal memory footprint
Step 1. We create a simple class that is inherited from the built-in set class.
By inheriting from the ‘set’ class, our UserEmails class gains all methods and functionalities of sets such as adding or removing elements from a set, performing operations such as union, intersection and difference.
Step 2. Instead of using the default constructor __init__, we use an alternative approach by @classmethod for reading emails from a text file.
And that's all! 😊 A few lines of code, and you have a powerful, reusable class.
What is happening here:
We use the ‘with’ statement to ensure the file is properly closed after reading. If you don't use the ‘with’ statement, it is time to start.
Next, we have generator expressions to read each line of the file, strip any whitespaces and create a generator of the resulting email addresses.
Finally, we return to a new instance of the class with the generator of email addresses as its arguments. This allows the method to create a new instance based on the file's contents, without having to manually parse the file or create a list of email addresses.
What if you have emails stored in a json file? Just add another @classmethod for reading from the json file, so ours will be:
By inheriting ‘set‘, you can manage emails like this:
All code with unittest is on GitLab.
With the UserEmails class and its class methods, you can easily manage and manipulate sets of email addresses in your Python code. By leveraging the power of sets and object-oriented programming, you can streamline your email address processing and make your code more efficient and maintainable.