繁体   English   中英

Swifter 库如何为对象引入新属性?

[英]How Does the Swifter Library Introduce a New Attribute to Objects?

最近,我发现了一个名为swifter的有用库,用于加快 python 中 pandas 系列的处理速度。 我确信它在后台做了很多矢量化处理和优化,但我很好奇它是如何通过导入来为 pandas 系列或数据框 object 引入新属性的。 拿这个最小的代码。

#!/usr/bin/env python3
# encoding: utf-8
import pandas as pd # Version 1.4.1
import numpy as np # Version 1.22.3
samples:int=2**20
colname:str='Value'
frame=pd.DataFrame(data={colname:np.random.randint(low=0, high=45353, size=samples)})

import swifter # Version 1.22.3 The following line throws an attribute error without this import
frame[colname].swifter # With swifter imported, this is swifter.SeriesAccessor object

这看起来真的很神奇,因为我认为 import 语句可以引入新的类、函数等,但不能改变命名空间中已经存在的对象的 API(可用方法)。 这只是在某种程度上与我在 OOP 范式中对象如何工作和交互的心理 model 相冲突。 任何关于它是如何完成的指导,或者它是否使用 python 语言的一些更深层次的高级特性都会很棒。

当您导入模块或 package 时,Python 会加载并执行其中的代码。

当您import swifter swifter 时, Python 会加载swifter.__init__文件,其中包含:

if "modin.pandas" in sys.modules:
    register_modin()

当条件为真时,执行register_modin 一般来说,当你导入一个模块或一个package时,除了在本地scope中注册一些变量、函数或类外,代码没有副作用。

为了避免魔法,好的做法是这样的:

from swifter import register_modin
register_modin()

看看pandas.api.extensions.register_dataframe_accessor

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM