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?
2 Answers 2
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
3 Comments
dotnotation for python 3.x? mine is 2.x. If I do what you say, I get ValueError: Attempted relative import in non-package. all files are at root.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.
__init__.py), I can runinterface.pywithout errors. I suspect there is something else going on in one of the files, or perhaps you have another file calledradio.pysomewhere else that is being imported.