How are import statements in plpython handled?

2019-02-03 05:12发布

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?

1条回答
够拽才男人
2楼-- · 2019-02-03 05:39

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.

Yes, this will affect performance.

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(...)
$$;

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

查看更多
登录 后发表回答