Python: Importing Modules of Modules
Question: I currently have the directory structure

    
    
    - module
        - __init__.py
        - foo.py
        - bar.py
    

I want to use function definitions from both `foo.py` and `bar.py` so have
written this:

    
    
    import module
    
    module.foo.fooFunction()
    module.bar.barFunction()
    

However I am getting the error `'module' object has no attribute 'foo'`. What
is the problem here?


Answer: first, it should be `__init__.py`, not `init.py`. Now, `__init__.py` is what
sets up your modules namespace.

if `__init__.py` is empty, then to use `fooFunction`, you'd need to import
`foo` too. It doesn't automatically get imported with `module`.:

    
    
     import module.foo
     module.foo.fooFunction()
    

If you don't like that, you could do:

    
    
    # __init__.py
    import foo
    import bar
    
    # script
    import module
    module.foo.fooFunction()
    

See what happened there? Since `__init__.py` imports `foo`, when you `import
module`, it in turn imports `foo` and `bar` into it's namespace. So, when you
go to access it in your script, `module` already has a `foo` submodule
imported into it's namespace.

You can even import names directly into the module namespace from foo or bar:

    
    
    # __init__.py
    from foo import fooFunction
    
    # script
    import module
    module.fooFunction()
    

