8-Bit Borges
8-Bit Borges

Reputation: 10033

Python - import module which imports module

I have three scripts in the same location:

   /__init__.py
    interface.py
    radio.py
    playlist.py

playlist.py has child classes stored, like:

class playlist1(radio):
    '''child class'''

and radio.py has the parent class:

class radio(object):
    '''parent class'''

I'm trying to run interface.py, which has:

if __name__ == "__main__":
    from playlist import *

in playlist.py I have this import, on its turn:

from radio import radio

but when I run interface.py, I get the following error:

ImportError: cannot import name radio

I use python 2.x. what's wrong?

Upvotes: 1

Views: 151

Answers (2)

FMc
FMc

Reputation: 42411

Your description of the situation has omitted a crucial part: the package where these modules live. For example, if they live in the foo package, the situation would look like this:

foo/
    __init__.py
    interface.py
    radio.py
    playlist.py

In that context, there are two common ways for the playlist module to import names from the radio module:

# 1. Fully qualified.
from foo.radio import radio

# 2. Relative import.
from .radio import radio

The second approach is strongly recommended because it leaves no room for ambiguity.

You also haven't told us how you are running interface.py. Those details can affect the importing situation as well.

If you are organizing code in packages, you need to follow a conventional project structure. In this layout, you would tend to work in the project root. Also you need a proper setup.py file. Here's what it might look like:

# ----
# Directory layout.
some_project/
    foo/
        __init__.py
        interface.py
        playlist.py
        radio.py
    setup.py

    # You work at this level.

# ----
# interface.py 

from playlist import radio

def main():
    print radio

# ----
# playlist.py

from .radio import radio

# ----
# radio.py

radio = 123

# ----
# setup.py

from setuptools import setup

setup(
    name     = 'foo',
    version  = '1.0',
    zip_safe = False,
    packages = ['foo'],
    entry_points = {
        'console_scripts': [
            'foobar = foo.interface:main',
        ],
    },
)

# ----
# Install stuff for dev work (ie in "editable" mode).
pip install -e .

# ----
# Run the command line entry point.
foobar

Upvotes: 1

Shobeir
Shobeir

Reputation: 127

I think you just need to make an empty file called

__init__.py 

in the same directory as the files. That will let Python2 knows that it's okay to import from this directory. Then use your code.

Upvotes: 0

Related Questions