How to simulate packages?

Jason Scheirer jason.scheirer at gmail.com
Thu Aug 21 20:52:01 CEST 2008


On Aug 21, 11:26 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
wrote:
> En Thu, 21 Aug 2008 13:04:51 -0300, Daniel <daniel.watr... at gmail.com>  
> escribi :
>
> > I have a project that I've decided to split into packages in order to
> > organize my code better.  So what I have looks something like this
>
> > src
> >   -module1
> >     -mod1_file.py
> >   -module2
> >     -mod2_file.py
>
> > Everytime I run mod2_file.py I need to import mod1_file.py.  Right now
> > I'm using an ugly little thing to do my import (see below).  Isn't
> > there some python mechanism to handle packages?
>
> Sure - Python *has* packages, you don't have to "simulate" them.
> Readhttp://docs.python.org/tut/node8.html#SECTION008400000000000000000
>
> --
> Gabriel Genellina

You can use relative imports, so in mod2_file.py you could

import ..module1.mod1_file as mod1

To pull in a dependent submodule. Also, I think you are thinking about
__init__.py?

package/
  __init__.py
  mod1/
    mod1.py
  mod2/
    mod2.py

And in your __init__.py you issue something like

import mod1
import mod2

if you need them loaded as soon as your package is imported, but you
may omit that and import piecemeal in your scripts as each one needs
functionality:

from mypackage.mod2 import just_this_one_function

Etc etc etc. But really if you only have a single Python file living
in each subdirectory, you are likely Doing It Wrong and your code
might just make more sense as:

package/
  __init__.py
  intuitively_named_submodule1.py
  intuitively_named_submodule2.py
  intuitively_named_submodule3.py

Where your intuitively named submodules are all logical groupings of
functionality. Remember that they don't ALL get imported right away,
in fact, only __init__.py is imported by default, so if that's missing
or doesn't import the other submodules by default, you have to
explicitly

import package.intuitively_named_submoduleN

each time you want to import a submodule.

Modules and packages: http://docs.python.org/tut/node8.html
Relative imports: http://www.python.org/dev/peps/pep-0328/



More information about the Python-list mailing list