4

I have a module structured as follows:

/module __init__.py /submod_1 __init__.py submod_1_class.py /submod_2 __init__.py submod_2_class.py 

but I find it incredibly annoying to have to import a class within submod_1_class.py with:

from module.submod_1.submod_1_class import my_class 

What I would prefer to be able to type is:

from module import my_class 

I have browsed through the site-packages folder and looked through popular modules like numpy, but I haven't been able to figure out how, for example:

import numpy a = numpy.array([1,2,3,4,5]) 

can be used when the definition of numpy array objects is buried deep within several subfolders of the numpy package.

2
  • 5
    Add some __init__.py files to define what should be accessible from each module. For example, if you have one in /module that includes from submod_1.submod_1_class import class, then from outside the module you can from module import class. To stick with numpy, for example, this line means that everything defined in this file can be imported straight from numpy. Commented Mar 23, 2015 at 23:39
  • 2
    @jonrsharpe Please put that in an answer, so you can get points for the upvote I want to give you. Commented Mar 23, 2015 at 23:49

1 Answer 1

2

You can use __init__.py files to define what can be imported from a given module. A very simple addition to your structure, for example, would draw up Class from submod_1_class such that external users can simply from module import Class.

/module __init__.py from submod_1 import Class /submod_1 __init__.py from submod_1_class import Class submod_1_class.py /submod_2 submod_2_class.py 

In numpy, for example, the top-level __init__.py contains a line that reads:

from .core import * 

This means everything defined within /core/__init__.py is available externally directly in the numpy namespace, even though it may actually be buried deep in some complex structure.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.