migrating to packages

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Oct 3 22:53:56 EDT 2007


gherzig at fmed.uba.ar writes:

> The MYCLASES.py file contains the A class, so i can use

> from MYCLASES import A
> a = ()
> 
> Using the "package mode" (wich looks fine BTW), having the simple
> MYCLASES/
>      __init__.py
>      A.py
> 
> forces my (i guess) to use the
> from MYCLASES.A import A

Yes, that's the namespace structure you've got with the above
filesystem structure.

(Incidentally, "MYCLASES" is a poor name for the package; it's
misspelled, refers to "classes" when it's really a package, and should
be all lower-case. I'll refer below as though the package is named
"mypackage" and the module is named "foo", with a class named "Foo".)

> which is not what i want, because the big amount of files i will
> have to modify

If you want, instead, to do "from mypackage import foo", then that's
where the package's '__init__' module is useful.

    mypackage/
        __init__.py
        foo.py

Simply have the '__init__' module do this::

    from foo import Foo

That way, the class 'Foo' is bound again to the name 'Foo' in the
namespace of the 'mypackage' package, and becomes available as an
attribute. Then, other code can do::

    from mypackage import Foo

Note that it's *also* possible for code to continue to do:

    from mypackage.foo import Foo

but that's no longer necessary, since the same object is now also
available by the name 'Foo' directly from 'mypackage' because you
explicitly put it there.

-- 
 \     "Pinky, are you pondering what I'm pondering?" "Uh, I think so, |
  `\     Brain, but we'll never get a monkey to use dental floss."  -- |
_o__)                                            _Pinky and The Brain_ |
Ben Finney



More information about the Python-list mailing list