[Tutor] Importing classes when needed
__peter__ at web.de
Mon May 30 09:45:33 CEST 2011
> Hello all,
> I have a question about how this is done the best way.
> In my project I have a folder with multiple file parsers, like this:
> - src
> -- main.py
> -- parsers
> --- __init__.py
> --- parser1.py
> --- parser2.py
> The parsers just contain a class which do the work.
> When the user clicks a button, I want to show all available parsers and
> use the choosen one when the user clicks "ok".
> Is it ok to place the following code in the __init__.py?
> from parser1 import Parser1
> from parser2 import Parser2
> def get_parsers():
> return [Parser1(), Parser2()]
> If so, is it ok to do a get_parsers() everytime the user clicks a
> button? Because that will initialize the parsers over and over again,
If you only need lazy instantiation, not lazy import, one solution is
from parser1 import Parser1
from parser2 import Parser2
_parsers = None
if _parsers is None:
_parsers = [Parser1(), Parser2()]
More information about the Tutor