Module imports during object instantiation
Ritesh Raj Sarraf
rrs at researchut.com
Wed Aug 15 15:16:15 EDT 2007
On Aug 15, 11:42 pm, Neil Cerutti <horp... at yahoo.com> wrote:
> On 2007-08-15, Ritesh Raj Sarraf <r... at researchut.com> wrote:
> > Or am I terribly missing something that you are trying to tell ?
>
> I didn't see log = Log() in your example. Sorry for the
> excursion.
>
> Are you sure os.name is 'posix' on your system?
>
Here again for you:
In [6]: cat rick.py
IPython system call: cat rick.py
import os, sys
class Log:
def __init__(self, verbose, lock = None):
self.VERBOSE = bool(verbose)
self.lock = bool(lock)
if self.lock:
self.dispLock = threading.Lock()
else:
self.dispLock = None
if os.name == 'posix':
try:
import foobar
except ImportError, e:
print >> sys.stderr, e
self.platform = 'posix'
self.color = get_colors()
elif os.name in ['nt', 'dos']:
self.platform = 'microsoft'
try:
import SomeModule
except ImportError, e:
# comment out next line before going to prod...
print >> sys.stderr, e
self.color = None
else:
self.color = SomeModule.get_colors_windows()
else:
self.platform = None
self.color = None
In [7]: from rick import Log
In [8]: log = Log(verbose = True)
No module named foobar
---------------------------------------------------------------------------
exceptions.NameError Traceback (most
recent call last)
/tmp/<ipython console>
/tmp/rick.py in __init__(self, verbose, lock)
18
19 self.platform = 'posix'
---> 20 self.color = get_colors()
21
22 elif os.name in ['nt', 'dos']:
NameError: global name 'get_colors' is not defined
In [9]: os.name
Out[9]: 'posix'
In [10]: import foobar
---------------------------------------------------------------------------
exceptions.ImportError Traceback (most
recent call last)
/tmp/<ipython console>
ImportError: No module named foobar
In [11]:
Okay!! Ignore line 20 for now because that is not what this whole
thread has been about. In the code, just 2 lines above "self.color =
get_colors()" you see the try/except import statements. Since there is
no "foobar" named module, an ImportError should have been thrown and a
relevant error message should have been printed.
With these example I'm just trying to prove that imports put into a
class' __init__() never get executed. They get executed if you put
them in any of the methods. (And I don't know why it is done this
way).
Ritesh
More information about the Python-list
mailing list