Module imports during object instantiation

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Tue Aug 14 09:23:09 CEST 2007


Ritesh Raj Sarraf a écrit :
> Bruno Desthuilliers wrote:
> 
>> Ritesh Raj Sarraf a écrit :
>>
>> 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.
>>
> 
> Yes, it should be called _each time_ I do an instantiation. But the point
> is, I'm doing it only once. And I don't see people instantiating multiple
> times.

You of course don't instanciate the same object more than once !-) What 
I meant is that, while you can be reasonably confident that the 
initializer will be call at least once (on instanciation), nothing 
prevents user code to directly call it as many times he wants.

> And even if you do, it should do separate imports.

Why so ? Using the import statement, modules are only imported once for 
a given process, you know ? And FWIW, what are the chances your running 
process will move from one platform to another ?-)

> log1 = Log()
> log2 = Log()
> 
> Both the objects are separate from each other in every manner and they share
> nothing.

How can you tell ? In the common case, they at least share a pointer to 
the Log class object, and depending on the implementation they can share 
other things too.

>> 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()
> 
> This is what I'm left with to do currently. But I doubt if that makes by
> classes independent and to "Just Work". If someone was to cut/paste just
> the class, it won't work.

Obviously not. But the module is the basic unit of code in Python.

> He'll have to go through the imports and figure
> out which one relates to the class he want's to import and add similar code
> to his.

I'm afraid you're confusing import, include and cut'n'paste (which is 
probably the worst possible code-reuse technic)... If someone wants to 
reuse your code, the normal way is to import your module (and eventually 
subclass yourmodule.SomeClass to extend/customize it).




More information about the Python-list mailing list