8

Want to learn the proper way for importing modules with folder

/garden
    __init__.py
    utilities.py
    someTools.py
    /plants
        __init__.py
        carrot.py
        corn.py

Inside /plants/__init__.py I have

__all__ = ['carrot', 'corn']
from . import *

inside carrot.py

def info():
    print "I'm in carrot.py"

When I do

import garden
garden.carrot.info()
# got correct result
I'm in carrot.py

My question is how do I correct namespace for utilities.py for example inside carrot.py and corn.py. I want to use function in utilities.py

Inside carrot.py when I

import utilities as util

# try use it and got global name error
util.someFunc()
# NameError: global name 'util' is not defined # 

Can I configure __init__.py in plants folder so that it import all the modules inside garden? Like utilities and sometools ? so I don't have to import utilities in both carrot.py and corn.py and be able to use utilities ?

2
  • 1
    Did you try if utilities.someFunc() works? The error is weird because if the interpreter couldn't import it, it should have raised ImportError Commented Dec 8, 2013 at 1:11
  • 1
    Please.. don't import * Commented Dec 8, 2013 at 1:11

1 Answer 1

5

note: all __init__.py files are empty.

main.py
app/ ->
    __init__.py
    package_a/ ->
       __init__.py
       fun_a.py
    package_b/ ->
       __init__.py
       fun_b.py

app/package_a/fun_a.py

def print_a():
    print 'This is a function in dir package_a'

app/package_b/fun_b.py

from app.package_a.fun_a import print_a
def print_b():
    print 'This is a function in dir package_b'
    print 'going to call a function in dir package_a'
    print '-'*30
    print_a()

main.py

from app.package_b import fun_b
fun_b.print_b()

if you run $ python main.py it returns:

This is a function in dir package_b
going to call a function in dir package_a
------------------------------
This is a function in dir package_a
  • main.py does: from app.package_b import fun_b
  • fun_b.py does from app.package_a.fun_a import print_a

If you have app in your PYTHONPATH, then from anywhere you can >>> from app.package_...

so file in folder package_b used file in folder package_a, which is what you want. Right??

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

1 Comment

is there a way I can import modules that under app/ for example I want to use main.func() in both fun_a and fun_b. Instead if import main in each file can I do something in init like import main as main so that in fun_a or fun_b I don't have to import main as main again and be able to use main.func() ??

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.