Maya Python project, importing from subdirectories

python
maya

#1

Hi, I’m trying to restructure and optimize my project and I can’t solve one issue so far.

So let’s say I have this structure:

parent_folder/ # This is a parent folder that is added into environment path, 
    project_name/ 
        moduleA/
                __init__.py
                file1.py
                file2.py
        moduleB/
                moduleC/
                    __init__.py
                    file1.py
                    file2.py
                __init__.py
                file1.py
                file2.py
        __init__.py
        globals.py

So, if I leave init files blank, then if I do this in Maya:

import project_name as pn

pn.moduleB.moduleC.file1.do_something()

It says that module pn does not have moduleB.

Now let’s assume I add “import moduleB” into the root init.py file. And try this:

from project_name.moduleB import moduleC

It will also state that moduleB has no moduleC. Etc. So basically it does not import anything that was not imported in init file. I do believe I’m doing something wrong here. How should I approach this?


#2

Ok, seems that if I specifically use this:

import project_name
import project_name.ModuleB
from project_name.ModuleB import ModuleC

then this works… is this the way to do it then?


#3

So when you import a package (folder with an __init__.py) file in it, all of the code in the in __init__.py file is executed. This creates the local namespace of the module object in python.

If you don’t have any code in __init__.py then the namespace is effectively empty, which is why you can’t just do:

import module
module.sub_module.some_function()

As sub_module was never imported.
But if you do:

import module.sub_module
module.sub_module.some_function()

This will work properly as you’ve imported the actual module that some_function was defined in.
Notice that you don’t actually need to import module first, as python’s import machinery is perfectly adept at determining which module you’re after in the package structure by the dotted name.

One other random aside, I would avoid naming a module globals as that is a reserved word in python, and could end up shadowing the globals builtin function.


#4

Aha, got it, and figured as much. I don’t think I ever encountered this behavior with Python 3.X or even newer Python 2 versions (might be wrong on 2.X).

One other random aside, I would avoid naming a module globals as that is a reserved word in python, and could end up shadowing the globals builtin function.

Thanks, not sure how to call it then, as “settings” is not right either :smiley:


#5

If its a bunch of global constants, const.py could work.

If its a bunch of global mutable objects, I would consider refactoring :slight_smile: