Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to go about creating a Python package with only one module?

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?

like image 695
petebachant Avatar asked Nov 12 '22 21:11

petebachant


1 Answers

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.

like image 92
Booboo Avatar answered Nov 15 '22 01:11

Booboo