Wax Cage
Wax Cage

Reputation: 788

How to import class from class included by that class

I got a weird problem that I wasn't been able to find answer all over the internet (or I don't know how to ask).

I have module AAA.py

from BBB import BBB
class AAA():
    def test(self):
        print 'AAAA'
        a = BBB()

and module BBB.py

class BBB():
    def __init__(self):
        print 'BBB'

then when I call

a = AAA()
a.test()

everything works as expected and I see output

AAAA
BBB

BUT when I try to import and use class AAA from module BBB.py

from AAA import AAA
class BBB():
    def __init__(self):
        print 'BBB'

I get following error

ImportError: cannot import name AAA

Any suggestions? I cant create circular dependencies in Python? I am using version Python 2.7.6 on Ubuntu

Upvotes: 1

Views: 118

Answers (2)

glglgl
glglgl

Reputation: 91017

Indeed - if AAA.py imports something from BBB.py at top level and vice versa, it doesn't work as intended.

There are two ways you can solve it:

  1. Import the modules from each other. This way they are both present as their namespace and will be filled during the import process.

    So just do import BBB and use BBB.BBB() for instantiating the class:

    import BBB
    class AAA():
        def test(self):
            print 'AAAA'
            a = BBB.BBB()
    
  2. Do the import where you need it:

    class AAA():
        def test(self):
            from BBB import BBB
            print 'AAAA'
            a = BBB()
    

    This way the link between the two modules is "looser" and not so tight.

Upvotes: 1

Federico Amici
Federico Amici

Reputation: 11

When you want to use a module in another one, you have to import it and so use import your_module. You have to type your_module.foo() if you want to use a method inside it. With the instruction from your_module import attr1, foo1, [...] you are modifying the module's global variables, so that you can use attr1 or the method foo1 as if they were in your module. A concrete example is: if you want to use the math module, you type import math and when you want to use the constant pi you type math.pi, but if you are sure there will be no clash with the other names, you'll type from math import pi and you will use the constant pi as if you declared it in your module.

Upvotes: 1

Related Questions