Recursive import: 'import' vs. 'from ... import ...'

I have two files that should use different functions from each other.

file1.py

import file2   # from file2 import y2

def x1():
    print "x1"

def x2():
    print "x2"
    file2.y2()

file2.py

import file1   # from file1 import x1

def y1():
    file1.x1()
    print "y"

def y2():
    print "y2"

if __name__ == "__main__":
    y1()

I would like to know why use import file1works, but import only a specific function from file1 ( from file1 import x1) not?

Traceback (most recent call last):
  File "file2.py", line 1, in <module>
    from file1 import x1
  File "file1.py", line 1, in <module>
    import file2
  File "file2.py", line 1, in <module>
    from file1 import x1
ImportError: cannot import name x1

I read about import:

import X

Imports a module Xand creates a link to this module in the current namespace. Then you need to determine the finished path of the module to access a specific attribute or method from within the module (for example: X.nameor X.attribute)

from X import *

X ( , _) .

, , () , , X. X , X.name . name , . X , - , .

.

+4
2

, import :

def x1():
    print "x1"

def x2():
    print "x2"
    file2.y2()

from file2 import y2

, . from x import y , , from ... import ..., , , , , , y2 .

+3

bharel, , , , .

x import y, , , ( , , ).

x import * , , x

, ( )

try exceptions:

try:
    from images.serializers import SimplifiedImageSerializer
except ImportError:
    import sys
    SimplifiedImageSerializer = sys.modules[__package__ + '.SimplifiedImageSerializer']

:

( ) Python

-1

All Articles