2

I have a structure as

name_folder:
    tobeused.py
    name_folder:
          __init__.py
          models.py
          radial.py

In module tobeused.py I did from name_folder import models.

In module models.py I did from radial import rad (rad is function in radial.py)

When I run models.py directly, it works. But when I run tobeused.py an error shows :

ImportError: No module named 'radial'

How to work on this? Thanks

2 Answers2

1

add __init__.py file to your folder

tobeused.py
folder:
      __init__.py
      models.py
      radial.py

Detailed explanation : What is __init__.py for?

The import :

from folder.models import something
madjaoue
  • 5,104
  • 2
  • 19
  • 31
  • Are you sure you can't import it ? I just tested it on https://repl.it/repls/GrimySubduedCallbacks and it seems working. From which directory do you call `tobeused.py` ? – madjaoue Jul 17 '18 at 10:27
  • Edited the Q, the directory is also have same name `name_folder` –  Jul 17 '18 at 10:29
  • Why is it that way..? –  Jul 17 '18 at 10:34
  • 1
    It's `from package.module import function`, you can also do it like this : `from package import module` then use your module `module.function` – madjaoue Jul 17 '18 at 10:41
  • 1
    Thanks @madjaoue. –  Jul 17 '18 at 10:49
1

Change from radial import rad to from .radial import rad

The . allows the file to look locally rather than within the working directory.

Magnetron
  • 357
  • 1
  • 7
  • Thanks it worked. But in `models.py` I also actually have `from matplotlib import ...` which works, why this one works? –  Jul 17 '18 at 10:27
  • 1
    This import works because matplotlib is held within python's managed libraries, i.e. the ones installed by pip, whose directory is in the environment path. These can be imported from any location and they will still work, whereas your libraries are local. – Magnetron Jul 17 '18 at 10:36