Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError: cannot import name (not a circular dependency)

Tags:

python

I have the problem on importing the class in the same package, and it seems not a circular dependency problem. So I'm really confused now.

my-project/
   lexer.py
   exceptions.py

I declared an exception in exceptions.py and wants to use it in lexer.py:

exceptions.py:

class LexError(Exception):
    def __init__(self, message, line):
        self.message = message
        self.line = line

and in lexer.py:

import re
import sys

from exceptions import LexError
...

It shouldn't be circular dependency since lexer.py is the only file has import in it.

Thanks!!

like image 350
SPiCaRia Avatar asked Sep 27 '22 05:09

SPiCaRia


1 Answers

exceptions conflicts with builtin module exception.

>>> import exceptions
>>> exceptions.LexError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'LexError'
>>> from exceptions import LexError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name LexError

Use different module name.

like image 128
falsetru Avatar answered Sep 30 '22 08:09

falsetru