Module imports during object instantiation

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


Ritesh Raj Sarraf a écrit :
> Bruno Desthuilliers wrote:
> 
>> Ritesh Raj Sarraf a écrit :
>>>         if lock is None or lock != 1:
>>>             self.DispLock = False
>>>         else:
>>>             self.DispLock = threading.Lock()
>>>             self.lock = True
>>>
>>>         if os.name == 'posix':
>>>            self.platform = 'posix'
>>>            self.color = get_colors()
>>>
>>>         elif os.name in ['nt', 'dos']:
>>>             self.platform = 'microsoft'
>>>             
>>>             try:
>>>                 import SomeModule
>>>             except ImportError:
>>>                 self.Set_Flag = None
>>>             
>>>             if self.Set_Flag is not None:
>>>                 self.color = SomeModule.get_colors_windows()
>>>
>>>         else:
>>>             self.platform = None
>>>             self.color = None
>>>
>>> When I create an object the "import" part never gets executed. Is there a
>>> reason behind it ?
>> what does "print os.name" yields ?
> 
> On Windows: nt
> On Linux: posix

Mmm... I guess you didn't understood my question. I do know the os 
module. You assert the "import" is never executed. Since it's only 
executed on a non-posix platform, I asked on what platform you where 
testing.


> 
>>> I mean I'd like to keep my class as independent as I want. So that when
>>> later I need to use it somewhere else, I don't need to know if it depends
>>> on any modules.
>>  >
>>
>> Then pass the module to the initializer. Python's modules are objects...
>>
> 
> Yes, that's an option. But is that the only one?

No.

> To me it looks like an ugly way of doing.

Really ? Why so ? You say you want to keep your class "as independant" 
(you don't say from what, but...). Can you imagine a way to get less 
coupling than passing appropriate parameters to the initializer ?





More information about the Python-list mailing list