[Spambayes] A few code questions (Outlook oriented)

Moore, Paul Paul.Moore at atosorigin.com
Wed Feb 19 10:25:44 EST 2003


From: David LeBlanc [mailto:whisper at oz.net]
> Now for the (probably) dumb question. I don't see how this works:
> 
> #manager.py, line 159
>         # determine which db manager to use, and create it.
>         ManagerClass = [PickleStorageManager, DBStorageManager][use_db]
>         self.db_manager = ManagerClass(bayes_base, mdb_base)
> 
> ManagerClass is two lists, one has pointers to the two classes and the other
> is the flag - and then it's called!?! eh? (I have no immediate plans to
> change this (if I ever do), but I would like to understand what's going on.)

[PickleStorageManager, DBStorageManager] is a list. You then *index* that
list via [use_db] (it's the multiple meanings of [...] that are confusing).
use_db is a boolean, taking values 0 or 1. So, the code is equivalent to

    if use_db:
        ManagerClass = DBStorageManager
    else:
        ManagerClass = PickleStorageManager

You then call ManagerClass (which is one of the two relevant classes) to
construct the manager object.

If you enjoyed this interlude, go and watch comp.lang.python, where there are
currently over 1000 messages on various proposals for how to write C's
conditional expression ( a ? b : c ) in Python. I'm sure this counts as some
evidence in that debate, but it needs more evidence like a forest fire needs
petrol...

(PS Mark, maybe you could rewrite the statement as a 4-line if, like I did
above, just for clarity?)

> BTW, how does it get to reference a global (use_db) without a "global"
> statement in the __init__ scope? I can't see where use_db gets used either?

The "global" statement is only needed if you want to *update* the global. Read
access to globals (when not shadowed by locals) is transparent.

Paul.



More information about the Spambayes mailing list