Question about import

Frank Millman frank at chagford.com
Thu Sep 10 03:12:29 EDT 2015


Hi all

My project comprises a number of modules, split into packages. Modules 
frequently need to access the contents of other modules, in the same or in a 
different package. I am getting better at it, but I still occasionally bump 
my head against circular imports, and have to fiddle around until it settles 
down again. Not ideal, I know.

I have just noticed something odd, and I wondered if it might provide a 
solution, or if it is a dangerous sidetrack. Here is a simple example -

/test
| start.py
  /a
  | aa.py
  /b
  | bb.py

start.py
    import a.aa
    import b.bb
    a.aa.aaa()
    b.bb.bbb()

aa.py
    import b
    def aaa():
        print('in aaa')
        b.bb.bbbb()
    def aaaa():
            print('in aaaa')

bb.py
    import a
    def bbb():
        print('in bbb')
        a.aa.aaaa()
    def bbbb():
        print('in bbbb')

c:\test>start.py
in aaa
in bbbb
in bbb
in aaaa

The surprising thing is that, within aa.py, I just have to say 'import b', 
and I can access 'b.bb.bbbb', and the same applies to 'bb.py'.

That makes me wonder if, in my project, I can import all modules inside 
'start.py', and then just use 'import package_name' inside each module?

Another question - I thought that, because aa.py and bb.py are in different 
sub-directories, I would have to set them up as packages by adding 
'__init__.py' to each one, but it works fine without that. What am I 
missing?

I am using python 3.4.

Any comments appreciated.

Frank Millman





More information about the Python-list mailing list