[Tutor] Importing classes when needed

Steven D'Aprano steve at pearwood.info
Tue May 31 00:21:36 CEST 2011


Timo wrote:
> 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

This gives you a stand-alone module called "main.py", and a separate 
package called "parsers". Is that intended?

I might think about putting this in a single package, perhaps like this:


- src
   -- my_application
      -- __init__.py
      -- __main__.py
      -- parsers
         --- __init__py
         --- parser1.py
         --- parser2.py


Now my_application is treated as a single package, containing a 
sub-package my_application.parsers.

The purpose of the __main__.py is that when you call the package from 
the command line, like this:

python -m my_application

the code inside __main__.py is executed.


> The parsers just contain a class which do the work.


Keep in mind that this is Python, not Java, and it's not compulsory to 
have one class per file. If the classes are small enough you are 
encouraged to put them in the one file.

Particularly if you use inheritance to delegate most of the work to a 
single parent class, something like this made up example:

from parsers import Parser1

class Parser2(Parser1):
     def parse(self, text):
         words = super(Parser2, self).parse(text)
         words = [s.lower() for s in words]
         return words



> 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()]

Certainly. You can have any code you like in __init__.py.


> 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?

Is that a problem?

If you prefer to always use the same two parsers, do this instead:

import parser1
import parser2

PARSERS = tuple(p() for p in (parser1, parser2))


Then instead of calling get_parsers(), just use PARSERS.



-- 
Steven



More information about the Tutor mailing list