Import functions directly from Python 3 modules
Question: I have the following folder structure for a Python 3 project where
`vehicle.py` is the main script and the folder `stats` is treated as a package
containing several modules:

[![enter image description
here](http://i.stack.imgur.com/ohzSm.png)](http://i.stack.imgur.com/ohzSm.png)

The `cars` module defines the following functions:

    
    
    def neon():
        print('Neon')
        print('mpg = 32')
    
    
    def mustang():
        print('Mustang')
        print('mpg = 27')
    

Using Python 3, I can access the functions in each module from within
`vehicle.py` as follows:

    
    
    import stats.cars as c
    
    c.mustang()
    

However, I would like to access the functions defined in each module directly,
but I receive an error when doing this:

    
    
    import stats as st
    
    st.mustang()
    # AttributeError: 'module' object has no attribute 'mustang'
    

I also tried placing an `__init__.py` file in the `stats` folder with the
following code:

    
    
    from cars import *
    from trucks import *
    

but I still receive an error:

    
    
    import stats as st
    
    st.mustang()
    # ImportError: No module named 'cars'
    

I'm trying to use the same approach as NumPy such as:

    
    
    import numpy as np
    
    np.arange(10)
    # prints array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    

How can I create a package like NumPy in Python 3 to access functions directly
in modules?


Answer: Put an `__init__.py` file in the `stats` folder (as others have said), and put
this in it:

    
    
    from .cars import neon, mustang
    from .trucks import truck_a, truck_b
    

Not so neat, but easier would be to use the `*` wildcard:

    
    
    from .cars import *
    from .trucks import *
    

This way, the `__init__.py` script does some importing for you, into its own
namespace.

Now you can use functions/classes from the `neon`/`mustang` module directly
after you import `stats`:

    
    
    import stats as st
    st.mustang()
    

