[Tutor] Importing classes when needed

Alexandre Conrad alexandre.conrad at gmail.com
Mon May 30 10:31:57 CEST 2011


2011/5/30 Timo <timomlists at gmail.com>:
> 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()]

It's not very common to find code inside __init__.py, but there's
nothing wrong with it. I usually do it when I need "shortcuts" to my
classes. For example, rather than doing this all over my code:

from mylib.parsers.parser1 import Parser1
from mylib.parsers.parser2 import Parser2

I add these lines in the __init__.py file, then I can:

from mylib.parsers import 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, right?

You could just return classes rather than instances. Although, I would
suggest you would just have a dictionary of parser names to parser
classes:

parsers = {"parser1": Parser1, "parser2": Parser2}

Then return a list of parsers strings to display to the user by doing:

def get_parsers():
    return parsers.keys()

And when the user selects a parser, you can lookup the key in the
dictionary and only instantiate the required class only when you need
it:

selected_parser = "parser1"
parser = parsers[selected_parser]
parser = Parser()
...

HTH,
-- 
Alex | twitter.com/alexconrad


More information about the Tutor mailing list