Module imports during object instantiation

Ritesh Raj Sarraf rrs at
Mon Aug 13 20:02:11 CEST 2007

Steve Holden wrote:

> Ritesh Raj Sarraf wrote:
>> class Log:
>>     def __init__(self, verbose, lock = None):
>>         if verbose is True:
>>             self.VERBOSE = True
>>         else: self.VERBOSE = False
> Better:
> self.VERBOSE = verbose
> or, if you suspect verbose might pass in a mutable value,
>          self.VERBOSE  bool(verbose)

Thanks for pointing this out.

> What's leading you to conclude the import isn't being executed? You
> realise, I trust, that the module's code will only be executed on the
> first call to __init__()?

Well. Putting it in a "try" inside __init__() doesn't do anything. The
import never happens. And thus if I make a call in any of the methods, it
fails with an error message. A NameError IIRC.
> You are right in assuming that __init__() is called once per instance
> created, and it's legitimate to make an import conditional in the way
> you have because of the "execute code only once" behavior - if the
> module is already in sys.modules then it won't be re-imported, the
> existing one will be used.

This is what even my understanding is. But am afraid to say that this
understanding is not implemented in Python. Have you tried doing this?
Does it work for you?

> Having said all that, I still don't see why you can't just put the
> try/except at the top level of your code and have color be a global. Why
> repeat the attempted import and the computation for each object you
> create? Alternatively, do it at the class level, so it's only executed
> once when the class is declared?

Hmmm!! This is where I might not have done my homework.

I just tried to import the same class (Log) the following way and it worked.

from module import Log

It worked.

Now I have some questions.

Going with your point of try/except imports at the top level, I am having
multiple imports at the top level for the multiple classes that I have in
the module. Not everything from the top level imports is required for the
class Log (Say, just one module is what is required).
So when I do a `from module import Log`, do all the modules at the  top
level get imported? My understanding says Yes, and if that's true, that's
bad IMO. (Sorry! I'd really not thought about this when reading about
Python module imports)

My ultimate goal is to make all my classes as independent as possible while
keeping them as lightweight as possible. If all top level module import
statements are getting executed during a `from module import class`, this
is _not_ lightweight IMO.

That's what led me to try imports in __init__() but unfortunately I haven't
seen that working for me even once.

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

More information about the Python-list mailing list