[Tutor] Possible to import imports?

Rob Kirkpatrick robert.d.kirkpatrick at gmail.com
Mon Jun 23 21:37:54 CEST 2008


It was mostly an exercise in understanding import orders/precedence but I
thought I might be able to use it to simplify imports for modules within a
package that might all use the same or similar standard imports.  The one I
see a lot of is modules in the package routinely importing os and sys so I
thought that if I could just import them once at the highest package level
then just have the modules import their parent package, things would be
cleaner.  You make a good point about that causing more confusion than it's
worth though, so I'll shelve that idea for the time being.

Funny though that I did try using something like foo.datetime but I must
have buggered up something cause I couldn't get it to work...

Thanks Kent!

On Mon, Jun 23, 2008 at 12:03 PM, Kent Johnson <kent37 at tds.net> wrote:

> On Mon, Jun 23, 2008 at 1:27 PM, Rob Kirkpatrick
> <robert.d.kirkpatrick at gmail.com> wrote:
> > I've googled a bit and tried some things on my own, but can't seem to
> > determine if it's possible to declare some standard library imports in
> one
> > package/module then import that package/module somewhere else and reap
> the
> > benefit of those initial imports.
> >
> > For example, if I have a setup like this:
> >
> > foo
> >   __init__.py
> >   bar
> >     __init__.py
> >     hello.py
> >
> > Could I put "import datetime" in foo's __init__.py and do an import of
> foo
> > from hello.py and start using datetime in hello.py without importing
> > datetime specifically in hello.py?
>
> Yes but it will be foo.datetime. The 'import datetime' in
> foo.__init__.py binds the name datetime in foo's module namespace.
>
> >  All the examples I see import all the
> > necessary standard library mods in the script/module that specifically
> uses
> > them so either what I want to do is not possible or a bad idea.
>  Thoughts?
>
> Why do this? For clarity, import the modules you need in the modules
> that need them.
>  import foo
>  foo.datetime...
> is just obscure IMO.
>
> Kent
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080623/cc0a7cdf/attachment.htm>


More information about the Tutor mailing list