Reputation: 87
I have a module written that I'd like to make a "package" some day. Right now I keep it in a subfolder with the same name inside a directory on my Python path (with an empty __init__.py
module in there with it). The problem is, to import these modules into other programs (and get Spyder's autocompletion to recognize the module's contents) I have to do something like
from modulename import modulename
or
import modulename.modulename as modulename
when I'd rather just
import modulename
I have tried making the __init__.py
inside the directory import everything from the module, but this doesn't work with Spyder's autocompletion. What's the appropriate way to do this? Numpy has many modules but still has some available at the top level namespace. It seems it does this by e.g.
import core
from core import *
Is this the route I should take, or is my problem the fact that the module name is the same as the folder name?
Upvotes: 6
Views: 1342
Reputation: 44108
As @Takahiro recommended, it's not a great idea to have a module with the same name as a package, but it's not an impossibility.
The __init__.py
in the modulename directory can be the following:
from .modulename import *
Then, for example, modulename.py in that directory might be:
def foo():
print('I am foo')
Then a client program could be
import modulename
modulename.foo()
or
from modulename import foo
foo()
etc.
Upvotes: 2
Reputation: 680
In the question title you ask about package with only one module but later you ask about Spyder. Anyways, I still believe this can be seen as a duplicate of this question from StackExchange.com. There is an excellent answer by the user Martijn Pieters. In order to provide some answer, not just a link I will sum it up bellow.
You do not have to create a package (subfolder) for your module (file). Just put your module.py
file into the root of your project where e.g. setup.py is
. From Martijn Pieters' answer:
You do the simplest thing that works for you. ...
Packages are useful for creating an additional namespace and/or for organising your code across multiple modules.
If you want examples: six is a distribution of just one module
There is a mention of such single module distributions on this page of the Python documentation.
Upvotes: 0
Reputation: 1262
Do not create a module with a same name within its package. http://docs.python.org/2/tutorial/modules.html#the-module-search-path
Upvotes: 0