是否可以将模块的引用分配给变量,然后使用变量而不是模块?

Per*_*uck 1 python python-2.7

假设我打开了一个文件来读取它的JSON数据:

import json
with open('filename', 'r') as infile:
    data = json.load(infile)
Run Code Online (Sandbox Code Playgroud)

对于我要使用的pickle文件:

import pickle
with open('filename', 'r') as infile:
    data = pickle.load(infile)
Run Code Online (Sandbox Code Playgroud)

现在我希望能够将我的代码段用于两种格式,即:

import json
import pickle

def read_data(filename, preferred_serializer)
    with open(filename, 'r') as infile:
        data = preferred_serializer.load(infile)
    return data
Run Code Online (Sandbox Code Playgroud)

并称之为:

data1 = read_data('file.pickle', pickle)
data2 = read_data('file.json', json)
Run Code Online (Sandbox Code Playgroud)

似乎是因为两者的工作jsonpickle共享相同的API load(infile).但我想知道它是否只是偶然发挥作用,或者这是否是定义的行为和合理的方法.

Mar*_*ers 5

这可以.模块只是对象,就像Python中的其他内容一样.

这不是偶然的,这是设计的,Python确实试图在命名中保持一致,因此通常会调用反序列化数据的函数load.再看marshal.load()另一个例子.或者yaml.load().

如果你想让它更通用,你可以存储load函数引用:

def read_data(filename, deserialize)
    with open(filename, 'r') as infile:
        data = deserialize(infile)
    return data

data1 = read_data('file.pickle', pickle.load)
data2 = read_data('file.json', json.load)
Run Code Online (Sandbox Code Playgroud)

毕竟,函数也只是对象,现在你使你的函数独立于可调用的名称.