1

I am having a lot of trouble understanding the python module import system.

I am trying to create a simple folder structure as follows.

SomeModule
   __init__.py
   AnotherModule
       AnotherModule.py
       __init__.py
       Utils
           Utils.py
           __init__.py

To use SomeModule i can do:

SomeModule.Foo()

Now inside AnotherModule.py I would like to import my Utils directory.

How come I have to do

import SomeModule.AnotherModule.Utils.Foo

why cannot I just do

import Utils.Foo
marsh
  • 2,592
  • 5
  • 29
  • 53
  • 2
    Because _explicit is better than implicit._ – wim Sep 16 '16 at 19:21
  • So a module must always know its full path? You can never move a module into another module directory without changing every import in the file? – marsh Sep 16 '16 at 19:23
  • You could have a go at `import .Utils` if you're feeling brave .. – wim Sep 16 '16 at 19:23
  • I don't think I'm understanding this question. When you say `import Utils.Foo`, you are implying that `Foo` is a *module* within the `Utils` *package*, otherwise the statement doesn't make sense. So you would have to have a `Foo.py` file within the `Utils` directory. – John Y Sep 16 '16 at 20:42
  • Also, I don't understand what you mean by "use" `SomeModule`. Where exactly is the statement `SomeModule.Foo()`? If that statement works, you're saying that there is a function (or callable class) named `Foo` within the `SomeModule` module or package. So it's in the `SomeModule/__init__.py` file? Why are you comparing the import behavior of a Foo function (in SomeModule) with a Foo module (in Utils)? – John Y Sep 16 '16 at 20:44
  • Regardless, you should read [PEP 328](https://www.python.org/dev/peps/pep-0328/). One thing you'll see there is that there is no such thing as a relative import without the `from` keyword. If the statement starts with `import` and has no `from`, then it is an absolute import, without exception. Also check out [this other Stack Overflow question](http://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time). There's a lot of information on that page, as well as many links right at the top which are likely to be relevant. – John Y Sep 16 '16 at 21:06

2 Answers2

0

To shorten up the actual function name that you'll have to call in your code, you can always do:

from SomeModule.AnotherModule.Utils import *

While this still won't allow you to get away with a shorter import statement at the top of your script, you'll be able to access all of the functions within .Utils just by calling their function name (i.e. foo(x) instead of SomeModule.AnotherModule.Utils.foo(x).

Part of the reason for the lengthy import statement goes to the comment from @wim . Have a look by typing import this in a python interpreter.

jcusick
  • 50
  • 7
0

put

import sys
import SomeModule.AnotherModule
sys.modules['AnotherModule'] = SomeModule.AnotherModule

in SomeModules __init__.py

marsh
  • 2,592
  • 5
  • 29
  • 53