1

I must be missing something simple here.

I have a directory structure:

maths/
    __init__.py
    test.py
    ...

    foo/
       __init__.py
       ...

    bar/
       __init__.py
       ...

In multiple files (but not all) I am using the path of the module - on Ubuntu for example - that path is /home/nebffa/Desktop/maths for some tasks. However, I have to compute the path of the maths package in all of those files - so I thought maybe it will be easier to just have it available via __init__.py. At least that's what I thought I could do based on reading up on __init__.py - maybe I'm wrong?

Anyway, attempts to make things available by putting them in the base __init__.py have failed to work so I think I might be misunderstanding this Python concept.

nebffa
  • 1,529
  • 1
  • 16
  • 26

2 Answers2

1

maths and maths.test are two separate modules, each with their own distinct namespace. You will need to explicitly import itertools in maths.test if you want it available there.

Also, python -m maths.test.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • I thought I could put things in `__init__.py` and they would automatically be imported upon trying to run/import test.py? – nebffa Oct 14 '13 at 04:07
  • No. Each module has its own distinct namespace. – Ignacio Vazquez-Abrams Oct 14 '13 at 04:07
  • @nebffa Why don't you just put `import itertools` in `test.py`? – Adam Oct 14 '13 at 04:08
  • @Adam I actually want to put the overall package's path in __init__.py - I am calling it in a number of places in my package and it is getting annoying. `itertools` is just a simple example I was trying to test. – nebffa Oct 14 '13 at 04:09
  • @IgnacioVazquez-Abrams `python -m maths.test` returns the exact same error. – nebffa Oct 14 '13 at 04:10
  • @nebffa: Of course it does. It doesn't magically make what you want work. – Ignacio Vazquez-Abrams Oct 14 '13 at 04:12
  • @nebffa A python package is a **module**, like any other. The difference is that, instead of having the module file called `module_name.py` it is called `package_name/__init__.py`. Doing `import package` searches for a directory called `package` that contains a `__init__.py` file and builds a **module** out of `__init__.py`. There is *no* special behaviour involved. Since in python there are no such things as "globals", you *always* have to import the things you need in a module, so you have to do when writing a package. – Bakuriu Oct 14 '13 at 07:34
1

If you run python test.py then __init__.py is not involved at all.

Adam
  • 16,808
  • 7
  • 52
  • 98