Home  >  Article  >  Backend Development  >  The black magic Metaclass that changes the rules of Python objects

The black magic Metaclass that changes the rules of Python objects

WBOY
WBOYforward
2023-04-14 11:43:031141browse

The black magic Metaclass that changes the rules of Python objects

The topic that Xiao Ming wants to share today is: the artifact of changing class definition-metaclass

When you see the title, you may wonder what is the use of changing the definition of a class? ? When do you need to use metaclass?

Today I will lead you to design a simple ORM framework and briefly analyze the principles of YAML, a serialization tool.

The God of Python classes-type

Speaking of metaclass, we must first understand the most basic concept that objects are instances of classes, and classes are instances of type. Repeat:

  1. Objects are instances of classes
  2. Classes are instances of type

In the object-oriented programming model, a class is equivalent to the design drawing of a house. The object is a house built based on this design drawing.

In the picture below, the toy model can represent a class, and the specific produced toy can represent an object:

The black magic Metaclass that changes the rules of Python objects

In short, a class is created The object's template.

And type is a template for creating classes, so we can create the classes we want through type.

For example, define a Hello class:

class Hello(object):
def hello(self, name='world'):
 print('Hello, %s.' % name)

When the Python interpreter loads the hello module, it will execute all the statements of the module in sequence, and the execution result is to dynamically create a Hello class object.

The type() function can not only check the type of a type or variable, but also create a new type based on the parameters. For example, the definition of the above class is essentially:

def hello(self, name='world'):
print('Hello, %s.' % name)
Hello = type('Hello', (object,), dict(hello=hello))

type( ) function creates a class object, passing in 3 parameters in sequence:

  • The name of the class class;
  • The collection of inherited parent classes. Note that Python supports multiple inheritance. If there is only one parent class , don’t forget the single-element writing method of tuple;
  • The method name of the class is bound to the function, as well as the field name and the corresponding value. Here we bind the function fn to the method name hello.

The class created through the type() function is exactly the same as writing the class directly, because when the Python interpreter encounters the class definition, it just scans the syntax of the class definition and then calls type() The function creates the class.

Under normal circumstances, we definitely use class Xxx... to define classes, but the type() function allows us to dynamically create classes, which means that Python, a dynamic language, supports dynamic creation during runtime kind. You may not feel how powerful this is. You must know that if you want to create a class during the static language runtime, you must construct a source code string and then call the compiler, or use some tools to generate bytecode implementation. In essence, it is dynamic compilation. very complicated.

What is metaclass

What is the relationship between type and metaclass? What exactly is metaclass?

I think metaclass is actually type or a subclass of type. By inheriting type and overloading the __call__ operator, you can make some modifications when the class object is created.

For the class MyClass:

class MyClass():
 pass

is actually equivalent to:

class MyClass(metaclass = type):
 pass

Once we set its metaclass to MyMeta:

class MyClass(metaclass = MyMeta):
 pass

MyClass is no longer represented by Native type creation will instead call MyMeta's __call__ operator overload.

class = type(classname, superclasses, attributedict)
## 变为了
class = MyMeta(classname, superclasses, attributedict)

For classes with inheritance relationships:

class Foo(Bar):
 pass

Python does the following operations:

  • Is there a __metaclass__ attribute in Foo? If so, Python will create a class (object) named Foo through __metaclass__
  • If Python does not find __metaclass__, it will continue to look for the __metaclass__ attribute in Bar (parent class) and try Do the same operation as before.
  • If Python cannot find __metaclass__ in any parent class, it will look for __metaclass__ in the module hierarchy and try to do the same operation.
  • If __metaclass__ is still not found, Python will use the built-in type to create this class object.

Imagine a silly example where you decide that all class attributes in your module should be in uppercase. There are several ways to do it, but one of them is to set __metaclass__ at the module level:

class UpperAttrMetaClass(type):
## __new__ 是在__init__之前被调用的特殊方法
## __new__是用来创建对象并返回之的方法
## 而__init__只是用来将传入的参数初始化给对象
## 你很少用到__new__,除非你希望能够控制对象的创建
## 这里,创建的对象是类,我们希望能够自定义它,所以我们这里改写__new__
## 如果你希望的话,你也可以在__init__中做些事情
## 还有一些高级的用法会涉及到改写__call__特殊方法,但是我们这里不用
def __new__(cls, future_class_name, future_class_parents, future_class_attr):
##遍历属性字典,把不是__开头的属性名字变为大写
newAttr = {}
for name,value in future_class_attr.items():
if not name.startswith("__"):
newAttr[name.upper()] = value
## 方法1:通过'type'来做类对象的创建
## return type(future_class_name, future_class_parents, newAttr)
## 方法2:复用type.__new__方法,这就是基本的OOP编程
## return type.__new__(cls, future_class_name, future_class_parents, newAttr)
## 方法3:使用super方法
return super(UpperAttrMetaClass, cls).__new__(cls, future_class_name, future_class_parents, newAttr)
class Foo(object, metaclass = UpperAttrMetaClass):
bar = 'bip'
print(hasattr(Foo, 'bar'))
## 输出: False
print(hasattr(Foo, 'BAR'))
## 输出:True
f = Foo()
print(f.BAR)
## 输出:'bip'

Design of a simple ORM framework

ORM's full name is "Object Relational Mapping", that is Object-relational mapping is to map a row of a relational database to an object, that is, a class corresponds to a table. In this way, it is easier to write code without directly operating SQL statements.

Now design the calling interface of the ORM framework. For example, if a user wants to operate the corresponding database table User through the User class, we expect him to write code like this:

class User(Model):
## 定义类的属性到列的映射:
id = IntegerField('id')
name = StringField('username')
email = StringField('email')
password = StringField('password')
## 创建一个实例:
u = User(id=12345, name='xiaoxiaoming', email='test@orm.org', password='my-pwd')
## 保存到数据库:
u.save()

The above interface passes through the regular The method is difficult or almost difficult to implement, but it is relatively simple through metaclass. The core idea is to modify the definition of the class through metaclass, save all Field type attributes of the class in an additional dictionary, and then delete them from the original definition. The parameters passed in by User when creating an object (id=12345, name='xiaoxiaoming', etc.) can be saved by imitating the dictionary implementation or directly inheriting the dict class.

其中,父类Model和属性类型StringField、IntegerField是由ORM框架提供的,剩下的魔术方法比如save()全部由metaclass自动完成。虽然metaclass的编写会比较复杂,但ORM的使用者用起来却异常简单。

首先定义Field类,它负责保存数据库表的字段名和字段类型:

class Field(object):
def __init__(self, name, column_type):
self.name = name
self.column_type = column_type
def __str__(self):
return '<%s:%s>' % (self.__class__.__name__, self.name)

在Field的基础上,进一步定义各种类型的Field,比如StringField,IntegerField等等:

class StringField(Field):
def __init__(self, name):
super(StringField, self).__init__(name, 'varchar(100)')
class IntegerField(Field):
def __init__(self, name):
super(IntegerField, self).__init__(name, 'bigint')

下一步,编写ModelMetaclass:

class ModelMetaclass(type):
def __new__(cls, name, bases, attrs):
if name == 'Model':
return type.__new__(cls, name, bases, attrs)
print('Found model: %s' % name)
mappings = dict()
for k, v in attrs.items():
if isinstance(v, Field):
print('Found mapping: %s ==> %s' % (k, v))
mappings[k] = v
for k in mappings.keys():
attrs.pop(k)
attrs['__mappings__'] = mappings## 保存属性和列的映射关系
attrs.setdefault('__table__', name) ## 当未定义__table__属性时,表名直接使用类名
return type.__new__(cls, name, bases, attrs)

以及基类Model:

class Model(dict, metaclass=ModelMetaclass):
def __init__(self, **kw):
super(Model, self).__init__(**kw)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Model' object has no attribute '%s'" % key)
def __setattr__(self, key, value):
self[key] = value
def save(self):
fields = []
params = []
args = []
for k, v in self.__mappings__.items():
fields.append(v.name)
params.append('?')
args.append(getattr(self, k, None))
sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join(params))
print('SQL: %s' % sql)
print('ARGS: %s' % str(args))

在ModelMetaclass中,一共做了几件事情:

  1. 在当前类(比如User)中查找定义的类的所有属性,如果找到一个Field属性,就把它保存到一个__mappings__的dict中,同时从类属性中删除该Field属性(避免实例的属性遮盖类的同名属性);
  2. 当类中未定义__table__字段时,直接将类名保存到__table__字段中作为表名。

在Model类中,就可以定义各种操作数据库的方法,比如save(),delete(),find(),update等等。

我们实现了save()方法,把一个实例保存到数据库中。因为有表名,属性到字段的映射和属性值的集合,就可以构造出INSERT语句。

测试:

u = User(id=12345, name='xiaoxiaoming', email='test@orm.org', password='my-pwd')
u.save()

输出如下:

Found model: User
Found mapping: id ==> 
Found mapping: name ==> 
Found mapping: email ==> 
Found mapping: password ==> 
SQL: insert into User (id,username,email,password) values (?,?,?,?)
ARGS: [12345, 'xiaoxiaoming', 'test@orm.org', 'my-pwd']

测试2:

class Blog(Model):
__table__ = 'blogs'
id = IntegerField('id')
user_id = StringField('user_id')
user_name = StringField('user_name')
name = StringField('user_name')
summary = StringField('summary')
content = StringField('content')
b = Blog(id=12345, user_, user_name='xxm', name='orm框架的基本运行机制', summary="简单讲述一下orm框架的基本运行机制",
 content="此处省略一万字...")
b.save()

输出:

Found model: Blog
Found mapping: id ==> 
Found mapping: user_id ==> 
Found mapping: user_name ==> 
Found mapping: name ==> 
Found mapping: summary ==> 
Found mapping: content ==> 
SQL: insert into blogs (id,user_id,user_name,user_name,summary,content) values (?,?,?,?,?,?)
ARGS: [12345, 'user_id1', 'xxm', 'orm框架的基本运行机制', '简单讲述一下orm框架的基本运行机制', '此处省略一万字...']

可以看到,save()方法已经打印出了可执行的SQL语句,以及参数列表,只需要真正连接到数据库,执行该SQL语句,就可以完成真正的功能。

YAML序列化工具的实现原理浅析

YAML是一个家喻户晓的 Python 工具,可以方便地序列化 / 逆序列化结构数据。

官方文档:https://pyyaml.org/wiki/PyYAMLDocumentation

安装:

pip install pyyaml

YAMLObject 的任意子类支持序列化和反序列化(serialization & deserialization)。比如说下面这段代码:

import yaml
class Monster(yaml.YAMLObject):
yaml_tag = '!Monster'
def __init__(self, name, hp, ac, attacks):
self.name = name
self.hp = hp
self.ac = ac
self.attacks = attacks
def __repr__(self):
return f"{self.__class__.__name__}(name={self.name}, hp={self.hp}, ac={self.ac}, attacks={self.attacks})"
monster1 = yaml.load("""
--- !Monster
name: Cave spider
hp: [2,6]
ac: 16
attacks: [BITE, HURT]
""")
print(monster1, type(monster1))
monster2 = Monster(name='Cave lizard', hp=[3, 6], ac=16, attacks=['BITE', 'HURT'])
print(yaml.dump(monster2))

运行结果:

Monster(name=Cave spider, hp=[2, 6], ac=16, attacks=['BITE', 'HURT']) 
!Monster
ac: 16
attacks: [BITE, HURT]
hp: [3, 6]
name: Cave lizard

这里面调用统一的 yaml.load(),就能把任意一个 yaml 序列载入成一个 Python Object;而调用统一的 yaml.dump(),就能把一个 YAMLObject 子类序列化。

对于 load() 和 dump() 的使用者来说,他们完全不需要提前知道任何类型信息,这让超动态配置编程成了可能。比方说,在一个智能语音助手的大型项目中,我们有 1 万个语音对话场景,每一个场景都是不同团队开发的。作为智能语音助手的核心团队成员,我不可能去了解每个子场景的实现细节。

在动态配置实验不同场景时,经常是今天我要实验场景 A 和 B 的配置,明天实验 B 和 C 的配置,光配置文件就有几万行量级,工作量不可谓不小。而应用这样的动态配置理念,就可以让引擎根据配置文件,动态加载所需要的 Python 类。

对于 YAML 的使用者也很方便,只要简单地继承 yaml.YAMLObject,就能让你的 Python Object 具有序列化和逆序列化能力。

据说即使是在大厂 Google 的 Python 开发者,发现能深入解释 YAML 这种设计模式优点的人,大概只有 10%。而能知道类似 YAML 的这种动态序列化 / 逆序列化功能正是用 metaclass 实现的人,可能只有 1% 了。而能够将YAML 怎样用 metaclass 实现动态序列化 / 逆序列化功能讲出一二的可能只有 0.1%了。

对于YAMLObject 的 load和dump() 功能,简单来说,我们需要一个全局的注册器,让 YAML 知道,序列化文本中的 !Monster 需要载入成 Monster 这个 Python 类型,Monster 这个 Python 类型需要被序列化为!Monster 标签开头的字符串。

一个很自然的想法就是,那我们建立一个全局变量叫 registry,把所有需要逆序列化的 YAMLObject,都注册进去。比如下面这样:

registry = {}
def add_constructor(target_class):
registry[target_class.yaml_tag] = target_class

然后,在 Monster 类定义后面加上下面这行代码:

add_constructor(Monster)

这样的缺点很明显,对于 YAML 的使用者来说,每一个 YAML 的可逆序列化的类 Foo 定义后,都需要加上一句话add_constructor(Foo)。这无疑给开发者增加了麻烦,也更容易出错,毕竟开发者很容易忘了这一点。

更优雅的实现方式自然是通过metaclass 解决了这个问题,YAML 的源码正是这样实现的:

class YAMLObjectMetaclass(type):
def __init__(cls, name, bases, kwds):
super(YAMLObjectMetaclass, cls).__init__(name, bases, kwds)
if 'yaml_tag' in kwds and kwds['yaml_tag'] is not None:
cls.yaml_loader.add_constructor(cls.yaml_tag, cls.from_yaml)
cls.yaml_dumper.add_representer(cls, cls.to_yaml)
## 省略其余定义
class YAMLObject(metaclass=YAMLObjectMetaclass):
yaml_loader = Loader
yaml_dumper = Dumper
## 省略其余定义

可以看到,YAMLObject 把 metaclass 声明成了 YAMLObjectMetaclass,YAMLObjectMetaclass则会改变YAMLObject类和其子类的定义,就是下面这行代码将YAMLObject 的子类加入到了yaml的两个全局注册表中:

cls.yaml_loader.add_constructor(cls.yaml_tag, cls.from_yaml)
cls.yaml_dumper.add_representer(cls, cls.to_yaml)

YAML 应用 metaclass,拦截了所有 YAMLObject 子类的定义。也就是说,在你定义任何 YAMLObject 子类时,Python 会强行插入运行上面这段代码,把我们之前想要的add_constructor(Foo)和add_representer(Foo)给自动加上。所以 YAML 的使用者,无需自己去手写add_constructor(Foo)和add_representer(Foo)。

Summary

This sharing mainly briefly analyzes the implementation mechanism of metaclass. By implementing an ORM framework and interpreting YAML source code, I believe you already have a good understanding of metaclass.

Metaclass is a black magic-level language feature of Python. It can change the behavior of a class when it is created. This powerful feature must be used with caution.

After reading this article, what do you think is the difference between decorators and metaclasses? Welcome to leave a message below to discuss with me. Remember to click three times in a row to refill!

The above is the detailed content of The black magic Metaclass that changes the rules of Python objects. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete