0

I have a python module ('my_module.py') and in it two functions 'A' and '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...)

asked Sep 22, 2014 at 5:31

2 Answers 2

3

Just import pandas at the start of the module.

It will be imported (and initialized) when my_module.py is imported or run, and it will be available for both functions. If several modules use pandas, import it at the start of each one - it will be imported only once per interpreter session.

Mockup example of mymodule.py:

import pandas
def A(foo):
 return pandas.do_something(foo)
def B(bar):
 return pandas.do_something_else(bar)
answered Sep 22, 2014 at 5:34
Sign up to request clarification or add additional context in comments.

3 Comments

I tried putting 'import pandas as pd' in the begining of my module but keep getting: NameError: global name 'pd' is not defined
@user2808117: You need to do that outside of any function, at the top level of the module.
for some reason one of the parameters passed to the functions triggered that error and it wasn't an imported related one. Sorry.
0

Use import pandas in your module my_module.py.

Inside your my_module.py

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

And similarly for B

answered Sep 22, 2014 at 5:36

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.