theprogrammer
theprogrammer

Reputation: 187

Module has no attribute error in python3

contents of io.py

class IO:
    def __init__(self):
        self.ParsingFile = '../list'

    def Parser(self):
        f = open(ParsingFile, 'r')
        print(f.read())

contents of main.py

import sys
sys.path.insert(0, "lib/")

try:
    import io
except Exception:
    print("Could not import one or more libraries.")
    exit(1)

print("Libraries imported")
_io_ = io.IO()

When I run python3 main.py I get the following error:

Libraries imported
Traceback (most recent call last):
  File "main.py", line 11, in <module>
    _io_ = io.IO()
AttributeError: module 'io' has no attribute 'IO'

Any idea what's going wrong?

Upvotes: 7

Views: 13371

Answers (3)

mshrbkv
mshrbkv

Reputation: 309

Your package name (io) conflicts with the Python library's package with the same name, so you actually import a system package.

You can check this by printing io.__all__.

Changing io.py to something else is probably the best way to go to avoid similar problems. Otherwise, you can use an absolute path.

Upvotes: 2

theprogrammer
theprogrammer

Reputation: 187

My file was called io. It seems that there already exists a package called io which caused the confusion.

Upvotes: 7

The4thIceman
The4thIceman

Reputation: 3889

try

from io import IO

That worked for me when trying to import classes from another file

this has more information:

Python module import - why are components only available when explicitly imported?

Upvotes: 0

Related Questions