Module imports during object instantiation

James Stroud jstroud at mbi.ucla.edu
Fri Aug 10 18:17:55 EDT 2007


Ritesh Raj Sarraf wrote:
> Hi,
> 
> I've been very confused about why this doesn't work. I mean I don't see any
> reason why this has been made not to work.
> 
> class Log:
> 
>     def __init__(self, verbose, lock = None):
> 
>         if verbose is True:
>             self.VERBOSE = True
>         else: self.VERBOSE = False
> 
> 
>         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 ?
> 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.
> 
> Currently, the way I'm left is to globally go and import the module and set
> a flag there.
> 
> 
> Ritesh

You do realize your import statement will only be called for nt and dos 
systems don't you?

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list