0

Consider the following folder structure:

main
 |
 |- misc/helpers.py
 |
 |- src/script.py

I have a python script located in main/src/ that calls another script containing helper functions located in main/misc/. This path is added to the sys.path variable at the top of script.py. Importantly, modules are loaded in script.py and not within the helper functions.

The issue is that any function in helpers.py that depends on a module fails with a NameError and yells that it cannot find the module. Traceback image is included. For example, one function requires Pandas, which is imported as pd at the top of script.py. I get the error NameError: name 'pd' is not defined'. I'm trying to understand the logic of my mistake and find a solution.

Example traceback

ricniet
  • 115
  • 6
  • Can you show the exact traceback (maybe this would help more people) – theX Jun 25 '20 at 20:26
  • ... as well as the code that produces the error. – Ronald Jun 25 '20 at 20:52
  • It looks like module A imports modules B and C and then you want module C to have access to module B and it doesn't. Is that the problem? – Dennis Sparrow Jun 25 '20 at 22:40
  • @DennisSparrow Yes, that's right -- some functions in B rely on C but it doesn't find them within A. – ricniet Jun 26 '20 at 16:21
  • @Ronald it's included in the image. `trelloHelpers.get_board_json(id=board_df.index[0])` is the call to the function in the imported module. The error is thrown after it hits `x = pd.Series([1,2,3])` because it cannot find the Pandas module, which is imported outside the function. – ricniet Jun 26 '20 at 16:25

1 Answers1

0

An importing module gets access to the names defined in an imported module, but this doesn't work in the other direction: an imported module does not get access to the names in the importing module.

So if your helpers.py script needs Pandas, for example, it should import Pandas itself, and not rely on its importer to make it available. Each module should take care of itself.

Having each module import what it needs is the normal and easiest thing to do, but if you really want to inject names into an imported module, there is a relevant discussion at Is there anything like Python export?.

Dennis Sparrow
  • 938
  • 6
  • 13