Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: what does "import" prefer - modules or packages?

Suppose in the current directory there is a file named somecode.py, and a directory named somecode which contains an __init__.py file. Now I run some other Python script from this directory which executes import somecode. Which file will be imported - somecode.py or somecode/__init__.py?

Is there even a defined and reliable search order in which this is resolved?

Oh, and does anyone have a reference to official documentation for this behavior? :-)

like image 267
oliver Avatar asked May 18 '11 19:05

oliver


People also ask

What is the difference between import module and from module import in Python?

The difference between import and from import in Python is: import imports the whole library. from import imports a specific member or members of the library.

Are Python modules the same as packages?

A Python package is nothing but a collection of modules along with a __init__.py file. The modules can also be arranged in hierarchy of folders inside a package. Just by adding an empty __init__.py file to the in the folder, Python knows it is a Package.

Is used in Python to import module from packages?

We can import modules from packages using the dot (.) operator. Now, if this module contains a function named select_difficulty() , we must use the full name to reference it.

Is import a module 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.


1 Answers

Packages will be imported before modules. Illustrated:

% tree .
.
|-- foo
|   |-- __init__.py
|   `-- __init__.pyc
`-- foo.py

foo.py:

% cat foo.py 
print 'you have imported foo.py'

foo/__init__.py:

% cat foo/__init__.py
print 'you have imported foo/__init__.py'

And from interactive interpreter:

>>> import foo
you have imported foo/__init__.py

I have no idea where this is officially documented.

Edit per comment: This was performed with Python 2.7 on Mac OS X 10.6.7. I also performed this using Python 2.6.5 on Ubuntu 10.10 and experienced the same result.

like image 124
jathanism Avatar answered Sep 28 '22 12:09

jathanism