Search code examples
pythonimportpython-module

Python : from module import * in __init__


Here is a simple case: I want to define a module in python name robot. So, I have a folder named robot with these two files:

__init__.py:

from test import a

test.py:

a = "hello world"

Now, when I import robot in the interpreter, the robot namespace includes test and a. However, I only want it to include a. Why this odd behavior?


EDIT:

Here's a slightly more representative example of what I want to achieve:

Given the following files:

__init__.py:

from spam import a
import ham

spam.py:

a = "hello world"

ham.py:

b = "foo"

Can I have a robot namespace containing a and ham at its top level but not spam?


Solution

  • You have created not just a module but a package. A package contains its submodules in its namespace (once they have been imported, as you imported test here). This is as it should be, since the usual way of using packages is to provide a grouping of several modules. There's not much use to making a package with only one module (i.e., one contentful .py file) inside it.

    If you just want a one-file module, just create a file called robots.py and put your code in there.

    Edit: See this previous question. The answer is that you should in general not worry about excluding module names from your package namespace. The modules are supposed to be in the package namespace. If you want to add functions and stuff from submodules as well, for convenience, that's fine, but there's not really anything to be gained by "covering your tracks" and hiding the modules you imported. However, as described in the answers to that question, there are some hackish ways to approximate what you want.