Search code examples
pythoninterfaceprotocols

What to use in replacement of an interface/protocol in python


I am making a chess game and wanted to make a standard piece interface/protocol. Python does not have those in the language, so what am I supposed to use? I read a bit about factories, but I'm not sure how they would help. Thanks in advance!


Solution

  • In short, you probably don't need to worry about it at all. Since Python uses duck typing - see also the Wikipedia article for a broader definition - if an object has the right methods, it will simply work, otherwise exceptions will be raised.

    You could possibly have a Piece base class with some methods throwing NotImplementedError to indicate they need to be re-implemented:

    class Piece(object):
    
        def move(<args>):
            raise NotImplementedError(optional_error_message) 
    
    class Queen(Piece):
    
        def move(<args>):
            # Specific implementation for the Queen's movements
    
    # Calling Queen().move(<args>) will work as intended but 
    
    class Knight(Piece):
        pass
    
    # Knight().move() will raise a NotImplementedError
    

    Alternatively, you could explicitly validate an object you receive to make sure it has all the right methods, or that it is a subclass of Piece by using isinstance or isubclass. Note that checking the type may not be considered "Pythonic" by some and using the NotImplementedError approach or the abc module - as mentioned in this very good answer - could be preferable.

    Your factory just has to produce instances of objects having the right methods on them.