Member-only story
How To Create Custom Classes in Python Without Going Meta
Use the power of Python Metaclasses without using Metaclasses
Working with Python metaclasses is extremely powerful and allows you to do very nifty things. One of those nifty things is customized class creation. With customized class creation, you can, for example, realize a plugin system or dynamically set attributes’ default values.
Unfortunately, working with metaclasses is not only very powerful but also a more advanced (and sometimes tedious) concept of Python. And, even if you are a Python God, you might still run into issues with metaclasses and go like…
For example, inheriting from multiple classes with different metaclasses doesn’t work because it results in a metaclass conflict. The only way to solve metaclass conflicts is via manual intervention, and this can be extremely difficult — almost like brain surgery. This becomes even worse if a metaclass is introduced in a new version of a library you are using. Suddenly, nothing works anymore, and you have to dive deep down into the details of the library code to resolve that conflict. This doesn’t sound good.
So, the question is: How can library developers and newbie Python developers enjoy the benefits of customized class creation without worrying to break stuff?
PEP-487 and Python 3.6+ to the rescue.
In this post, I give you a brief introduction to customized class creation in python as introduced in PEP-487, with a small example of how to use it to create a simple plugin system.
Are you ready? Let’s get started.
Customized Class Creation
Let’s say you want to build an application where people can talk to different kinds of cloud data warehouses (DWH) like BigQuery, Redshift, or Snowflake. For the sake of this example, let’s say that all DWHs have a different way of establishing a connection, which is very specific to each DWH. A user should be…