2

I'm starting with Python, and I'm developing a simple program. But the interpreter shouts at me when I try to import a method in a separate file. Here is my configuration:

file A.py (main):

import os
import copy
import locale
from C import some_function1, some_function2, some_function3

file B.py:

import os
from C import some_function

file C.py:

import os
import time
from B import some_class
from B import some_class

It does not work and I get the following error:

Traceback (most recent call last):
  File "G:/XXXX/XXXX/A.py", line 5, in <module>
    from C import some_function1, some_function2, some_function3
  File "G:\XXXX/XXXX\C.py", line 3, in <module>
    from B import some_class
  File "G:\XXXX/XXXX\B.py", line 3, in <module>
    from C import some_function
ImportError: cannot import name 'some_function4' from 'C' (G:\XXXX/XXXX\Fonctions.py)

But it works when in the B file I replace from C import some_function by import C and when I use C.some_function4 instead of just some_function4.

My program works well and I have at least one option that allows me to continue, but I would like to know what I'm doing wrong ... I guess it's a self-inclusion problem as I already had in C ++ but I do not know python well enough to see how I could fix that.

Someone can help me with that?

Ondrej K.
  • 8,841
  • 11
  • 24
  • 39
Varden
  • 101
  • 5
  • 2
    I guess it is the issue of circular imports. Check if functions are dependent on each other. – Sumit S Chawla Jan 29 '19 at 13:33
  • Hi ! I guess this answer may help you to understand the problem : https://stackoverflow.com/questions/744373/circular-or-cyclic-imports-in-python – Clem G. Jan 29 '19 at 13:57
  • 1
    after some research I think I understood my mistake. 'from C import some_function' only works if 'import C' has already been called. I thought it would not have to import the whole file, but it only allows you to not have to write 'C.some_function' (which is already nice) so you have to call 'import C' at least once, so in the main file will be ample for me. Thanks to you Clem for your very useful link. – Varden Jan 29 '19 at 15:28
  • 1
    "'from C import some_function' only works if 'import C' has already been called" - no, that's incorrect. Running `import C` earlier may sometimes kludge around a circular import problem due to changing the initialization order, but it's neither a prerequisite for `from` imports nor a solution to circular import problems. – user2357112 Jan 30 '19 at 20:54

0 Answers0