Python Import Looping issues

Source: Internet
Author: User

When invoking a function in Django, an error occurs:
can‘timport get_user_info

found that the import of this module Ah, why the import is not successful? The issue of importing loops is the tip of the person. Open the "Python core programming" module of the import cycle that chapter, see To understand.

Simulate a simple scene

There is a function a () in a.py, which calls for function B () in b.py, and the function C () in b.py needs to call a (), which is a circular import. The code looks like this:

from  b import  bprint   '--- ------This is module a.py----------'  def  a   () :  print  Span class= "hljs-string" > "Hello, a"  B () A ()  
fromimport aprint‘----------this is module b.py----------‘def b():    print"hello, b"def c():    a()c()

Run: Python a.py, error is as follows:

Zy@zy: ~/code/python/test/import$ Python a.pyTraceback(most recent):  File "a.py", line1,inch< module>From B Import BFile "/home/zy/code/python/test/import/b.py", line1,inch< module>From a import aFile "/home/zy/code/python/test/import/a.py", line1,inch< module>From B Import BImporterror:Cannot import name b

In the a.py import b.b (), in the import of B file, but also to import a file, a file to import B file, this is a dead loop, nature is not allowed.

Workaround:
    • You can place the statements of the import module in a local (function). As shown below:
print   '---------This is module a.py----------'  def  Span class= "Hljs-title" >a   () :  print   "Hello, a"  from  b import  b b () A ()  
‘----------this is module b.py----------‘def b():    print"hello, b"def c():    fromimport a    a()c()

Run: Python a.py, the results are as follows:

zy@zy:~/code/python/test/import$ module a.py----------module b.py----------module a.py----------hello, ahello, bhello, ahello, bhello, b

Python Import Looping issues

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.