Module imports during object instantiation

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Mon Aug 13 04:09:54 EDT 2007


Ritesh Raj Sarraf a écrit :
> On Aug 11, 3:17 am, James Stroud <jstr... at mbi.ucla.edu> wrote:
>> You do realize your import statement will only be called for nt and dos
>> systems don't you?
>>
> 
> Yes. I would like to load a Windows Python Module (which is, say a
> specific implementation for Windows only) in such a condition where I
> find that the platform is Dos/NT.
> 
> Loading it globally doesn't make sense because when from the same
> class an object is created on a non-windows platfom, it would be
> waste. It would either ImportError or else just load the module and
> never use it.
> 
> As per my understanding __init__ is executed only once during object
> creation. For such situations (that I've explained above), I think
> __init__() is the correct place to put imports.


Nope.

The initializer will be called *each time* you instanciate the class. 
And nothing prevents client code from calling it explicitelly as many 
times as it wants  - ok, this would be rather strange, but this is still 
technically possible. What I mean that you have no assurance about the 
number of times an initializer will be called.


wrt/ your problem, remember that top-level code is executed when the 
module is loaded (either as a main program or as an imported module). 
The canonical solution to os-specific imports is to handle them at the 
top-level:

if os.name == 'posix:
   from some_posix_module import get_colors
elif os.name in ['nt', 'dos']:
   from some_nt_module import get_windows_color as get_colors
else:
   get_colors = lambda: None # or any other sensible default value...

class SomeClass(object):
   def __init__(self, *args, **kw):
     self.colors = get_colors()



More information about the Python-list mailing list