Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Python Unlocked

You're reading from   Python Unlocked Become more fluent in Python—learn strategies and techniques for smart and high-performance Python programming

Arrow left icon
Product type Paperback
Published in Dec 2015
Publisher
ISBN-13 9781785885990
Length 172 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Arun Tigeraniya Arun Tigeraniya
Author Profile Icon Arun Tigeraniya
Arun Tigeraniya
Arrow right icon
View More author details
Toc

Registry pattern


Key 9: Adding functionality from anywhere in code to class.

This is one of my favorite patterns and comes to help a lot. In this pattern, we register classes to a registry, which tracks the naming to functionality. Hence, we can add functionality to the main class from anywhere in the code. In the following code, Convertor tracks all convertors from dictionary to Python objects. We can easily add further functionalities to the system using the convertor.register decorator from anywhere in the code, as follows:

class ConvertError(Exception):

    """Error raised on errors on conversion"""
    pass


class Convertor(object):

    def __init__(self,):
        """create registry for storing method mapping """
        self.__registry = {}

    def to_object(self, data_dict):
        """convert to python object based on type of dictionary"""
        dtype = data_dict.get('type', None)
        if not dtype:
            raise ConvertError("cannot create object, type not defined...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image