Question on class module import

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Dec 4 18:55:23 EST 2009


On Fri, 04 Dec 2009 15:10:49 -0800, monkeyboy wrote:

> Hello,
> 
> I want to write a wrapper class around a windows dll. If I put the class
> in a module "Refprop.py" then import the class where I want to use it,
> does the whole module get read by the interpreter or just the class
> code?...

Every import always involves a module. You can't import a class in 
isolation. Even if you use the form "from module import object", the 
entire module gets loaded first, in order to access the object.



> For example if I say the following in "Refprop.py" does the code above
> the class statement get run on an import 

Only the first time you import it. After that, the module is cached.


> or should the loadLibrary call
> be made in the constructor...

Do you want to call loadLibrary every time you create an instance? Then 
put it in the constructor.

Do you want to call loadLibrary only once? Then leave it were it is.



> the code below appears to work OK, I just
> want to be sure I understand what happens on an import call....

Python looks in sys.modules to see if the module has already been loaded. 
If it has, it returns the module.

If not, it searches for the module. If it finds it, then it executes the 
code in the module, caches the module object in sys.modules, and returns.



-- 
Steven



More information about the Python-list mailing list