简体   繁体   English

如何初始化python模块?

[英]How to initialise a python module?

I have a python module ('my_module.py') and in it two functions 'A' and 'B'. 我有一个python模块('my_module.py'),其中有两个函数'A'和'B'。

They both require a 3rd module (say pandas). 它们都需要第三个模块(例如熊猫)。

Is there a way to load pandas as part of the module so it'll be accessible to both functions? 有没有办法将熊猫加载为模块的一部分,以便两个功能都可以访问它? (trying to avoid importing pandas per function call...) (试图避免每个函数调用导入熊猫...)

Or do I have to convert this into a package and load pandas as part of the init ? 还是我必须将其转换为一个包并在初始化过程中加载熊猫? (trying to avoid that since I don't want an extra directory...) (试图避免这种情况,因为我不需要额外的目录...)

Just import pandas at the start of the module. 只需在模块开始处import pandas

It will be imported (and initialized) when my_module.py is imported or run, and it will be available for both functions. 将在导入或运行my_module.py时将其导入(并初始化),并且这两个功能均可用。 If several modules use pandas , import it at the start of each one - it will be imported only once per interpreter session. 如果几个模块使用pandasimport每一个开始-它只会每一次解释器会话中导入。

Mockup example of mymodule.py : mymodule.py样机示例:

import pandas

def A(foo):
    return pandas.do_something(foo)

def B(bar):
    return pandas.do_something_else(bar)

Use import pandas in your module my_module.py . 在模块my_module.py使用import pandas

Inside your my_module.py 在您的my_module.py

def A(sth):
    return pandas.module(sth)

And similarly for B 对于B同样

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

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