Python: importing a module

Suppose I have a python fibo.py model defined below:

#Fibonacci numbers module print "This is a statement" def fib(n): a,b = 0,1 while b < n: print b a, b = b, a+b def fib2(n): a,b = 0,1 result= [] while(b < n): result.append(b) a, b = b, a+b return result 

In my interpreter session, I do the following:

 >> import fibo This is a statement >>> fibo.fib(10) 1 1 2 3 5 8 >>> fibo.fib2(10) [1, 1, 2, 3, 5, 8] >>> fibo.__name__ 'fibo' >>> 

So far so good .. drag the translator:

 >>> from fibo import fib,fib2 This is a statement >>> fibo.__name__ Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'fibo' is not defined >>> 

I was expecting an error as I only imported fib and fib2. But I donโ€™t understand why the expression was printed when I imported only fib and fib2.

Secondly, if I change the module as:

 #Fibonacci numbers module print "This is a statement" print __name__ 

What should be the expected result?

+6
source share
2 answers

This is the expected behavior. When you import using from X import Y , the module is still loading and executing as described in the Language Reference . In fact, when you do

 from fibo import fib print("foo") import fibo 

prints This is a statement , and then foo . The second import does not print anything since the module is already cached.

The second module will print This is a statement , and then fibo . The module knows its name at boot time.

+9
source

Python must load the entire module in order to import anything from it. Python imports the entire module into the moduleโ€™s cache, but only the characters you display are visible to you. (If you import a second time, it will not start because the module is cached on the first import.)

+2
source

Source: https://habr.com/ru/post/917859/


All Articles