Python import modules inside folder

Want to know the correct way to import modules with a folder

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

Inside /plants/__init__.pyme

__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 to change the namespace for utilities.py, for example, inside carrot.pyand corn.py. I want to use the function inutilities.py

Inside carrot.pywhen i

import utilities as util

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

Can I customize __init__.pyin the folder with plants to import all the modules inside the garden? How are utilities and sometools? so I don’t need to import utilities in both carrot.py and corn.py and be able to use utilities?

+4
source share
1 answer

Note: all files __init__.pyare empty.

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

application / 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()

$ python main.py, :

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 : from app.package_b import fun_b
  • fun_b.py from app.package_a.fun_a import print_a

app PYTHONPATH, >>> from app.package_...

package_b package_a, . ??

+2

All Articles