Python ImportError: cannot import name X

This was strange, I had a bunch of classes in a file and was trying to import one of them from a file in a child folder.

The package looked like this:

/ <– “import child” was in here way on top
/child/ <– For every file in this folder, import it
/child/ <– Import a class in *Error*

The reason was that I was doing “import child” way on top before implementing the class I was importing in

I moved the “import child” line from the top of the to the constructor of the class I was implementing and it fixed the issue.

I hope this made sense :) (and I know it will to the person with this problem ;) )

Python ImportError: cannot import name X
Filed under: Python   Posted by: CodingRecipes



    Thanks a lot! That was a very useful post :D
    And yes, it made sense :P



    yes, kewl post, mr. snake-charmer — solved my problem too :) now i can continue choking the snake.


  3. luislope:

    and what happen if you hace a bouch of classes on:


    and now make a package like this:




  4. luislope:

    ok ok ok I got, niceeeee. thanks.


  5. Daniel:

    Thx for the info – it also solved my problem – but i had to reread your post quite often to understand it.

    The problem is a **circular Reference** – as child gets imported in parent, which also wants to import parts of parent.


  6. pointer:

    thanks a lot for the post. it does make sense to me.



    Thanks a lot, saved me a lot of searching :)


  8. ysa:

    thanks so much for solving my problem.

    ***would take “years” to find it.heheheeh…
    saved me a lot of searching [2]!


  9. AJ:

    You are putting the imports in your constructor? That seems a little weird (and extremely against the standards lol). Alternatively you could separate the parent code, and re-order the imports.

    For instance:
    / <–first import parent2, then children
    / <– part of parent code needed by children
    /children/ <– imports parent2
    /children/ <– same as before


  10. Mary:

    Thank you, thank you, thank you, thank you!


  11. Brian:

    I had this same issue using mod_python trying to import psycopg2. I had to move the

    import psycopg2


    def handler(req):
    import psycopg2


  12. John Villar:

    Can’t believe this was the error i was having. One million thanks to you pal!!! :-)



    Muy útil, muchas gracias.



RSS feed for comments on this post. TrackBack URL

Leave a comment