Parametrized module import

John Lenton jlenton at gmail.com
Thu Jul 8 18:25:25 CEST 2004


On 08 Jul 2004 16:28:21 +0200, Jacek Generowicz
<jacek.generowicz at cern.ch> wrote:
> 
> Yup ... but now I'm being put under pressure to make the API thus:
> 
>  import foo
>  foo.config....
> 
> which doesn't thrill me at all, for a plethora of implementation
> detail related reasons which are not interesting here.
> 
> Thanks for the poniter, anyway.

How ugly is this:

    import sys

    def __config():
        return sys._getframe(2).f_globals.get('__magic_config', None)

    def config(name):
        name = str(name)
        if name not in __mapping:
            raise RuntimeException, "unknown flavor " + name
        sys._getframe(1).f_globals['__magic_config'] = name

    def __default_bar(*a, **kw):
        print "I am the default"

    def __white_bar(*a, **kw):
        print "I am white"

    def __black_bar(*a, **kw):
        print "I am black"

    __mapping = {'bar': {None: __default_bar,
                         'white': __white_bar,
                         'black': __black_bar},
                 }

    for i in __mapping:
        globals()[i] = lambda *a, **kw: __mapping[i][__config()](*a, **kw)

I'd say about 6 in a fuglyness scale, but it might do what you want.
I'm sure there's an easyer way of putting things into the current
namespace, but this works.

-- 
John Lenton (jlenton at gmail.com) -- Random fortune:
bash: fortune: command not found



More information about the Python-list mailing list