Import functions directly from Python 3 modules
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()
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, 2022Comments
-
wigging almost 2 years
I have the following folder structure for a Python 3 project where
vehicle.py
is the main script and the folderstats
is treated as a package containing several modules: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 thestats
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 over 8 yearsimport stats.cars as c === from stats import cars as c
-
wigging over 8 yearsI tried the
__init__.py
approach and still get the error. -
wigging over 8 yearsI tried the
__init__.py
approach but I still get an error about the import not being seen. Please see my updated question. -
chepner over 8 yearsYou need to specify a relative import:
from .cars import *
. -
user2357112 over 8 yearsYeah, this is Python 2-style implicit relative importing. You need the explicit
.cars
relative import. -
wigging over 8 yearsok, I needed the
.cars
import instead of justcars
, thefrom stats.cars import *
also works