Question about extending the interperter

Fredrik Lundh fredrik at pythonware.com
Fri May 13 12:21:02 EDT 2005


"Eli" <elie at flashmail.com> wrote:

> Thanks for the answer; I should better explain my problem.

that's always a good idea ;-)

> So a solution would be creating 'function 1' which preprocess the input
> and calls the original function 1, than do so for any other function.
> This works, but there are *lots* of such enteries and I'm trying a
> general way of doing so.

can you extract a list of all available commands?  if so, you can
add a call dispatcher to your interface module, and use Python
code to generate wrappers for all your commands:

    # File: mymodule.py

    import _mymodule # import the C interface

    class wrapper:
        def __init__(self, func):
            self.func = func
        def __call__(self, *args):
            # prepare args in a suitable way. e.g
            args = " ".join(map(str, args))
            return _mymodule.callafunction(self.func, args)

    # get list of function names
    FUNCTIONS = "myfunc", "yourfunc"

    # register wrappers for all functions
    g = globals()
    for func in FUNCTIONS:
        g[func] = wrapper(func)

>>> import mymodule
>>> mymodule.myfunc("hello")
DEBUG OUTPUT: myfunc(hello) -> 10
10

if the names are available in some internal structure, you can also
add a function that returns a list of function names, so you can do:

    for func in _mymodule.getfunctionnames():
        g[func] = wrapper(func)

</F>






More information about the Python-list mailing list