0

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'


chriszumberge
  • 844
  • 2
  • 18
  • 33

1 Answers1

1

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.

jfaccioni
  • 7,099
  • 1
  • 9
  • 25
  • changed my ```parser.py``` to ```queryParser.py``` and the import in ```main.py``` to ```from queryParser import Parser``` and it worked perfectly. thank you – chriszumberge Apr 02 '20 at 15:01
  • 1
    I don't understand why this fixed the issue. If `parser.py` was in the current directory, that should have been found by the import first, before the standard library module, right? – John Gordon Apr 02 '20 at 15:04