from import and __init__.py

Terry Reedy tjreedy at udel.edu
Thu Mar 25 12:43:13 EDT 2010


On 3/25/2010 6:16 AM, egbert wrote:
> When I do 'from some_package import some_module'
> the __init__.py of some_package will be run.
> However, there will not be anything like a  package-module,
> and the effects of __init__.py seem all to be lost. Is that true ?

No. If you do

from sys import modules
print(modules.keys())

you will see both some_package and some_package.some_module among the 
entries. The first is the result of executing some_package/__init__.py. 
As usual, that code will *not* be re-exectured on subsequent imports 
involving some_package.


 > Or can I still do something useful with __init__.py ?
 > e

Some packages put something like 'from _default_stuff import *' in 
__init__.py with the intention that the package by used as

import package

perhaps [optionally] followed by

import package.specialized_stuff

Terry Jan Reedy






More information about the Python-list mailing list