简体   繁体   中英

Import variable from sub module through __init__.py in django

I am going through a problem which i cant import variables from __init__.py . I google my problem but i cant find any answer that i can understand.

my module structure is:

my_module/
    __init__.py
    sub_module/
        __init__.py
        module_file.py

Contents in my files is :

# my_module/__init__.py
from sub_module.module_file import show_variable

# sub_module/module_file.py
show_variable = "string needs to display"

But when i try to access variable from the sub_module

from my_module import show_variable

it through an error

ImportError: cannot import name show_variable

Is there any way to access my variable through __init__.py file ? Waiting for your valuable response. Thank you

Your example should work.

This works for me (2.7.6):

# my_module/__init__.py
from sub_module.module_file import show_variable

# my_module/sub_module/__init__.py (empty)

# my_module/sub_module/module_file.py
show_variable = 'string needs to display'

# main.py
from my_module import show_variable
print show_variable

From the parent directory of my_module:

>>> from my_module import show_variable
>>> print show_variable
string needs to display

You can also try this for a variation:

# my_module/__init__.py
from sub_module import show_variable

# my_module/sub_module/__init__.py
from .module_file import show_variable

Maybe something about how you've set up your package under Django. Where is your file that's loading my_module relative to the my_module package?

I've used this before to refactor a single module into a package with multiple files while keeping it a drop in replacement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM