How to assign a function to another function

Kurt Smith kwmsmith at gmail.com
Mon Sep 17 18:49:16 CEST 2007


On 9/17/07, Stefano Esposito <stefano.esposito87 at gmail.com> wrote:
> Hi all
>
> what i'm trying to do is this:
>
> >>>def foo ():
> ...     return None
> ...
> >>>def bar ():
> ...     print "called bar"
> ...
> >>>def assigner ():
> ...     foo = bar
> ...

You need to tell "assigner()" that foo doesn't belong to the local
(function) namespace, but rather comes from the global namespace:

In [1]: def foo():
   ...:     return None
   ...:

In [2]: def bar():
   ...:     print "called bar"
   ...:
   ...:

In [3]: def assigner():
   ...:     global foo
   ...:     foo = bar
   ...:
   ...:

In [4]: assigner()

In [5]: foo()
called bar

Kurt



More information about the Python-list mailing list