Module imports during object instantiation

Ritesh Raj Sarraf rrs at researchut.com
Mon Aug 13 20:08:15 CEST 2007


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. And even if you do, it should do separate imports.

log1 = Log()
log2 = Log()

Both the objects are separate from each other in every manner and they share
nothing.

> 
> 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. 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.

Ritesh
-- 
If possible, Please CC me when replying. I'm not subscribed to the list.




More information about the Python-list mailing list