如何处理plpython中的import语句? [英] How are import statements in plpython handled?

查看:96
本文介绍了如何处理plpython中的import语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个plypython函数,可以执行一些json魔术.为此,它显然会导入json库.

I have a plypython function which does some json magic. For this it obviously imports the json library.

在每次调用该函数时都调用了导入吗?我需要了解任何性能暗示吗?

Is the import called on every call to the function? Are there any performance implication I have to be aware of?

推荐答案

import在每个函数调用上执行.如果您在函数体内使用import语句编写了普通的Python模块,而在模块级别上却相反,则会得到相同的行为.

The import is executed on every function call. This is the same behavior you would get if you wrote a normal Python module with the import statement inside a function body as oppposed to at the module level.

是的,这会影响性能.

您可以通过以下方式缓存导入来解决此问题:

You can work around this by caching your imports like this:

CREATE FUNCTION test() RETURNS text
LANGUAGE plpythonu
AS $$
if 'json' in SD:
    json = SD['json']
else:
    import json
    SD['json'] = json

 return json.dumps(...)
$$;

这显然不是很漂亮,并且正在讨论实现此目的的更好方法,但是它们不会在PostgreSQL 9.4之前发生.

This is admittedly not very pretty, and better ways to do this are being discussed, but they won't happen before PostgreSQL 9.4.

这篇关于如何处理plpython中的import语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆