P
P
prostranstvovremya2019-04-19 17:16:05
Django
prostranstvovremya, 2019-04-19 17:16:05

Why is importing a class from a module through "." sometimes it works and sometimes it doesn't?

Hello!
While taking a video course on Django, I saw how classes from other files are imported through a dot. And myself, repeating the steps from the course, I can also import classes from another file through the construction. But I decided to create a small project, test one function, and in it my system swears at such an import. I get an error. And without a dot - it works.
from .models import Tag
from .A import A

Traceback (most recent call last):
  File "B.py", line 1, in <module>
    from .A import A
SystemError: Parent module '' not loaded, cannot perform relative import

I googled it by mistake, they offer different solutions, the most banal one is to remove the dot.
But I'm still interested in the reasons for this behavior. Because of which? How is a django module different from a regular python module?
Directory structure
├── A.py
└── B.py
I'm not sure how important the contents of the files are, but I'll give below
Short example
A.py
class A():
    a = 1
    b = 2
    def plus(self):
        c = self.a + self.b
        print(c)

B.py
from .A import A
a = A()
a.plus()

Соответственно ошибка, когда использую импорт с точкой
[email protected] ~/ImportTrouble $ python3 B.py 
Traceback (most recent call last):
  File "B.py", line 1, in <module>
    from .A import A
SystemError: Parent module '' not loaded, cannot perform relative import

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alternativshik, 2019-04-19
@alternativshik

there is probably no __init__.py file in the "module" directory, so it's not a module.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question