Returning a value from code string

Fredrik Lundh fredrik at pythonware.com
Sat Jan 28 07:51:03 CET 2006


Kirk McDonald wrote:

>      def __call__(self, args=None, **kwargs):
>          # We can pass in a name/value dictionary
>          if args: kwargs.update(args)
>          exec self.code
>          # We don't need a standard function if we're not returning
>          # anything
>          if locals().has_key('std_func_name'):
>              return std_func_name(**kwargs)

executing the code in a custom namespace is a lot cleaner:

    ns = {}
    ns["os"] = os # insert "preimported" values
    ns["app"] = app # insert "preloaded" objects
    exec self.code in ns
    try:
        func = ns["std_func_name"]
    except KeyError:
        pass
    else:
        func(**kwargs)

instead of using a standard function, you can let the code
objects talk to the application via a preloaded object or an
interface module.  e.g. instead of

    def std_func_name(app, args):
        app.something()

your code object could simply become

    app.something()

or, if std_func_name represents a specific event:

    def myfunc(args):
        app.something()

    app.register("event", myfunc)

(in the latter case, the event handler don't have to know
about Codeobj instances; all event callbacks are ordinary
callables)

</F>






More information about the Python-list mailing list