0

It looks simple, but I could not find a solution.

I display the problem below with the simplest example I could come up with.

(My classes are quiet more complex ;) )

file A.py

import os, sys
import B
from B import *
class _A():
    def __init__(self,someVars):
        self.someVars = someVars
    def run(self):
        print self.someVars

someVars = 'jdoe'
B._B(someVars)

file B.py don't match with import A

import A
from A import _A
class _B():
    def __init__(self,someVars):
        self.someVars = someVars
    def run(self):
        A._A(self.someVars)

with import A -> callback : cannot find _A

It only works when I do -

from A import * 

But and logically A functions are executed 2 times.

Thanks to all

Adam Hopkins
  • 6,837
  • 6
  • 32
  • 52
Karlova
  • 11
  • 1
  • 3
  • Its because import A doesn't import underscored classes. You are calling `A._A` instead of `_A`, when you do `from A import _A` its allowing you to call `_A` directly. Never use `from A import *`, always either use `import A` or `from A import _A`. You don't need both either, one will do. [Underscored Class imports](http://stackoverflow.com/questions/551038/private-implementation-class-in-python). [Import vs. from import](http://stackoverflow.com/questions/710551/import-module-or-from-module-import) – krc Aug 16 '16 at 17:34

2 Answers2

0

There is no need to first import X, then from X import Y. If you need Y (even if Y is *) do just from X import Y. This might be the cause of 2 times execution.

Also why have cyclic dependencies between modules A -> B, B -> A? Maybe they should be in one file then?

akarilimano
  • 1,034
  • 1
  • 10
  • 17
0

Because of cyclic dependency you are facing the import error, you can continue your work as:

File A.py:

import os, sys
#Below two import lines does cyclic dependency between file A and B which is wrong and will give import error, 
#commenting below two lines will resolve your import error
#import B 
#from B import * 
class _A():
    def __init__(self,someVars):
        self.someVars = someVars
    def run(self):
        print self.someVars

someVars = 'jdoe'
#B._B(someVars) #comment and respective logic should be moved in B file

Also, you should either use import A or from A import _A and if you use the later you should call the class directly as: _A(self.someVars) not as: A._A(self.someVars), this calling convention will be used for former import style(import A), for better understanding of external use of classes and module, you can refer following link: https://docs.python.org/3/tutorial/modules.html

justjais
  • 344
  • 3
  • 13