wigging
wigging

Reputation: 9170

Import functions directly from Python 3 modules

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?

Upvotes: 8

Views: 12260

Answers (4)

Def_Os
Def_Os

Reputation: 5467

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()

Upvotes: 12

lcerezo
lcerezo

Reputation: 31

Have you tried something like from cars import stats as c

You may also need a an empty __init__.py file in that directory.

host:~ lcerezo$ python
Python 2.7.10 (default, Oct 23 2015, 18:05:06)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from boto.s3.connection import S3Connection as mys3
>>>

Upvotes: 0

Yogesh Yadav
Yogesh Yadav

Reputation: 4745

You need to create __init__.py file in stats folder.

The __init__.py files are required to make Python treat the directories as containing packages. Documentation

Upvotes: 0

Stefan Yohansson
Stefan Yohansson

Reputation: 667

add empty __init__.py file in your stats folder and magic happens.

Upvotes: 0

Related Questions