Loading just in time
larry.bates at websafe.com`
Thu Jul 10 18:03:10 CEST 2008
D'Arcy J.M. Cain wrote:
> I am trying to create a utility module that only loads functions when
> they are first called rather than loading everything. I have a bunch
> of files in my utility directory with individual methods and for each I
> have lines like this in __init__.py:
> def calc_tax(*arg, **name):
> from calc_tax import calc_tax as _func_
> calc_tax = _func_
> return _func_(*arg, **name)
> This works the first time I call utility.calc_tax but if I call it
> again I get a "TypeError: 'module' object is not callable" error. Is
> there any way to do what I want or do I have to put everything back
> into a single file. Of course, I can simply change all my calls to
> utility.calc_tax.calc_tax(...) but I have a lot of code to change if I
> do that.
You are stuck in a futile battle called "premature optimization". I would
suggest that you stop worrying about any performance you would gain from doing
something like this. Python has been "highly" optimized to handle imports in a
very efficient way. Just put your functions in a file and import them.
from myfunctions import calc_tax, ...
Then you don't have to preface the function name with the module name.
More information about the Python-list