tyler314 / led_matrix

Micropython library used to control Adafruit's RGB LED matrix panel.
MIT License
3 stars 1 forks source link

microcontroller class API #8

Open untzag opened 7 years ago

untzag commented 7 years ago

a container to hold correspondences between natural names of output pins and pins themselves

will be subclassed on a board-by-board basis

untzag commented 7 years ago

consider making Microcontroller a singleton

tyler314 commented 7 years ago

@untzag Will looks at ways to implement a class as a singleton soon. Looks like there's more than one way to do it, leaning toward using MetaClasses though, perfect opportunity to code in uncharted territory. Semi-useful like on the matter: http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html

tyler314 commented 7 years ago

@untzag So it seems like this is the standard code for writing a metaclass for a singleton and I believe that I finally understand it.

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

I’m going to try and explain how this works. As you know, everything in Python is an object, including classes, and the classes we write are of type “type”. This Singleton class will be a parent of our Microcontroller class, but not in the traditional sense. The code above has a dictionary (_instances) that will store all instances of a class created when said class is created, of classes that inherit from this Singleton metaclass. (Side: They aren’t actually inheriting from the Singleton class, they will actually be of type Singleton). As you can see in the call method, we check to see if an instance of the class is stored in the dictionary, if there isn’t, then we create a new instance and store it away, if it does exist, we just return the pre-existing instance. We write this code in the call method, since when we create a new instance of a class (e.g. x = Microcontroller()), we are also “calling” the Metaclass since Microcontroller is now of type Singleton). This will result in the following code:

a = Microcontroller()
b = Microcontroller()
a is b

True