Link Search Menu Expand Document

Python Interfaces

The idea of the interface is that it describes how an object behaves. An interface expresses the role of an object in a system. In object-oriented programming (OOP), an interface is a set of an object’s publicly accessible approach, which associates with other parts of the function to interact with that object. Interfaces set clear boundaries and help developers organize the code better.

Informal Interface

Python does not consist of any keyword for an interface. In the dynamic language world, things are more inherent. The focus is on how an object behaves rather than its type/class.

Suppose an object that can fly and quack like a duck is considered a duck. In real-time, instead of inspecting an object’s type, the user invokes a technique that expects the object to have. If the object behaves the way the user expected, Observation is sufficient and move along. However, if it does not, it is a setback. To be safe, programmers often handle the exceptions in a try..except blocking or use hasattr to see if an object has an accurate method.

These conversational interfaces are protocols. Since they are informal, it may get formally enforced. They are mostly illustrated in the documentation or defined by convention. All the ‘magic’ methods as below help an object conforms to some protocols.

  • __len__
  • __ contain__
  • __iter__
  • - all
class Team:
    def __init__(self, members):
        self.__members = members

    def __len__(self):
        return len(self.__members)

    def __contains__(self, member):
        return member in self.__members

Animals = jungle(["Lion", "Panther", "Monkey"])
# Sized protocol
print(len(Animals))

# Container protocol
print("Lion" in Animals)
print("Panther" in Animals)
print("Rhyno" not in Animals)

By implementing the len and contains method, the user may now use the len() function on a jungle instance and check for association using the in operator. If the user adds the iter method to execute the iterate-able protocol, the user may able to do so as well.

for member in Animal:
    print(member)

Without implementing the iter method try to iterate over the jungle, an error “TypeError: ‘jungle’ object is not iterate-able.

Formal Interface

Formal Python interface is consists of ABC (Abstract Base Class) and a few more tools.

ABC.ABCMeta Class

To apply the subclass instantiation of abstract methods, the user needs to utilize Python’s built-in ABCMeta from the ABC module.

Rather than creating their metaclass, the programmer should use ABC.ABCMeta as the metaclass. Then, user may overwrite .subclasshook() in place of .instancecheck() and .subclasscheck(), as it generates a more reliable implementation of these precise methods.

The concept of ABCs is simple. Suppose the user defines abstract base classes. It defines specific techniques on the base classes as abstract methods. Any objects developing from these bases classes are required to implement those methods and since base classes are in use, if users see an object has our class as a base class, that is the object implementing the interface.

Virtual Class using ABC

After importing the ABC module, the Virtual subclass is very easy to implement using the .register () meta-method.

Note: if that class does not subclass ABC base class, it is still a subclass to ABC

@Bird.register
class Dog:
    pass
r = Dog()
issubclass(Dog, cat)
  True
isinstance(r, cat)
  True

Suppose Dog does not subclass our ABC class. It may register as a cat.

Other useful articles:


Back to top

© , Learn Python 101 — All Rights Reserved - Terms of Use - Privacy Policy