Import functions directly from Python 3 modules

10,540

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()
Share:
10,540
wigging
Author by

wigging

I enjoy programming in Swift, Objective-C, and Python. Visit my personal website, Twitter, and GitHub profiles for more information about myself.

Updated on June 19, 2022

Comments

  • wigging
    wigging almost 2 years

    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

    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?

  • Stefan Yohansson
    Stefan Yohansson over 8 years
    import stats.cars as c === from stats import cars as c
  • wigging
    wigging over 8 years
    I tried the __init__.py approach and still get the error.
  • wigging
    wigging over 8 years
    I tried the __init__.py approach but I still get an error about the import not being seen. Please see my updated question.
  • chepner
    chepner over 8 years
    You need to specify a relative import: from .cars import *.
  • user2357112
    user2357112 over 8 years
    Yeah, this is Python 2-style implicit relative importing. You need the explicit .cars relative import.
  • wigging
    wigging over 8 years
    ok, I needed the .cars import instead of just cars, the from stats.cars import * also works