0

Assume I have the following file structure:

A/
   __init__.py
   B.py

Inside __init.py__ I have the following:

__init__.py/
import numpy as np
import pandas as pd

Then inside the B.py I have the following:

B.py/
    from A import np
    print(np.linspace(0,10,10))

However, this code produces an error that no module named A. If for now, we do not consider the circular import problem which is not the case here. How can I import from

__init.py__

Since otherwise, all the imports I have in it will be useless. I recall a while ago I could run a code like above with no problem but now this is a problem.

I can just add the path to package A to sys.path but then every time I should run the command and is not even scalable or practical.

Does anyone why python is complaining and how I can import what I have in init.py?

math
  • 341
  • 4
  • 14
  • Why is B inside the A folder? Just move it into the parent directory – Nick is tired Jun 30 '21 at 08:22
  • No B is actually a script inside the package. If it is outside I have no problem. Just want to use the codes inside __init__.py in B. When writing from A import np this will run the __init__.py. This should work fine. This is why we place all the imports in __init__.py – math Jun 30 '21 at 08:25
  • Oh, well you can use `from . import np` in B and then in your main.py file elsewhere to run the code in B, you'd just use `import A.B` (or `importlib.reload(A.B)` if running it multiple times). If you want to run B standalone I can't understand why you'd want it as apart of the package though – Nick is tired Jun 30 '21 at 08:35
  • Does this answer your question? [How to import classes defined in \_\_init\_\_.py](https://stackoverflow.com/questions/582723/how-to-import-classes-defined-in-init-py) – UltraStudioLTD Sep 16 '21 at 09:23

0 Answers0