views:

1904

answers:

4

Suppose I have the following structure:

app/
  __init__.py
  foo/
    a.py
    b.py
    c.py
    __init__.py

a.py, b.py and c.py share some common imports (logging, os, re, etc). Is it possible to import these three or four common modules from the __init__.py file so I don't have to import them in every one of the files?

Edit: My goal is to avoid having to import 5-6 modules in each file and it's not related to performance reasons.

+4  A: 

No, they have to be put in each module's namespace, so you have to import them somehow (unless you pass logging around as a function argument, which would be a weird way to do things, to say the least).

But the modules are only imported once anyway (and then put into the a, b, and c namespaces), so don't worry about using too much memory or something like that.

You can of course put them into a separate module and import that into each a, b, and c, but this separate module would still have to be imported everytime.

balpha
+1  A: 

You can do this but it wouldn't be recommended practice (since it involves a wildcard import):

app/
    __init__.py
foo/
    a.py
    b.py
    c.py
    include.py <- put the includes here.
    __init__.py

Then in a.py etc would do:

from include import *

As I say, its not recommended though because wildcards are discouraged.

jkp
+3  A: 

Yes, but don't do it. Seriously, don't. But if you still want to know how to do it, it'd look like this:

import __init__

re = __init__.re
logging = __init__.logging
os = __init__.os

I say not to do it not only because it's messy and pointless, but also because your package isn't really supposed to use __init__.py like that. It's package initialization code.

Evan Fosmark
A: 

I have a similar question: What if you have some constants that are common to your modules. init.py seems like a reasonable place to put them, but then all the modules need to do

from __init__ import *

which just seems messy.

darkporter
If you have a question, you should post it as a question. This is not an answer to the question that was asked in this post.
TokenMacGuy
I think the answer is basically "don't put anything in `__init__.py`" which is fine.
darkporter