Search code examples
pythonpython-3.xpython-importimporterror

Python cannot import one of two identical classes int the same directory


When running a python script, I'm trying to import two different classes from two different scripts from the same directory. The first one works, the second one fails, for reasons I have not been able to figure out.

I took all of the useful code out of the imported scripts and made them identical except for the class names to try to limit the number of variables while I was testing solutions.

I had been following along these two guides when the issues occurred

I'm sure it's a mind-numbingly simple fix, but I have not yet been able to figure it out.

Thanks for your help.


Python Version

Python 3.6.9 :: Anaconda, Inc.

Folder Structure

  • MSAs
    • __init__.py
    • lexer.py
    • main.py
    • parser.py

File Contents

__init__.py

"""empty file"""

lexer.py

class Lexer():
    def __init__(self):
        self.hello = 'world'

parser.py

class Parser():
    def __init__(self):
        self.hello = 'world'

main.py

from lexer import Lexer
from parser import Parser

p = Parser()

Running the script from the MSAs folder

msas> python main.py

ImportError: cannot import name 'Parser'


Things the internet told me to try, and their results

I feel like a few of these are common sense that they did not work but I was attempting to exhaust all my options.

prefix the module name with a . if not using a subdirectory:

No module named '__main__.lexer'; '__main__' is not a package

change to import parser.Parser

No module named 'parser.Parser'; 'parser' is not a package

change to from . import Parser

AttributeError: module 'parser' has no attribute 'Parser'

insert the working directly into sys.path

ImportError: cannot import name 'Parser'

Switch the order of the import statements

ImportError: cannot import name 'Parser'



Solution

  • parser is a module in Python's standard library, so I believe your code is trying to import Parser from that file, not from your parser.py file. Since that object does not exist, you get the ImportError you see.