Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Importing Module

Tags:

python

Lets say I have a python model fibo.py defined as 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... restart the interpreter:

>>> 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 expected the error as I have only imported fib and fib2. But I don't understand why the statement was printed when I only imported 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?

like image 338
futurenext110 Avatar asked Jun 12 '12 08:06

futurenext110


People also ask

What does import module mean in Python?

Import in python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way. import module_name.

What are the three ways to import modules in Python?

So there's four different ways to import: Import the whole module using its original name: pycon import random. Import specific things from the module: pycon from random import choice, randint. Import the whole module and rename it, usually using a shorter variable name: pycon import pandas as pd.


2 Answers

This is expected behavior. When you import with from X import Y, the module is still loaded and executed, as documented in the Language Reference. In fact, when you do

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

will print This is a statement, followed by foo. The second import doesn't print anything as the module is already cached.

Your second module will print This is a statement followed by fibo. The module knows its own name at load time.

like image 70
Fred Foo Avatar answered Sep 23 '22 13:09

Fred Foo


Python has to load the whole module in order to import anything from it. Python imports the whole module into its module cache, but only the symbols you import are visible to you. (If you import a second time, it will not run; this is because the module is cached the first time it is imported.)

like image 36
jpaugh Avatar answered Sep 21 '22 13:09

jpaugh