Function declarations

Andrew Dalke dalke at acm.org
Sun Nov 19 00:23:09 CET 2000


Makhno asked:
>Is it possible to obtain a reference to a function before it has been
>'def'ined?
>
>eg:
>
>do_something(my_func)
>
>def my_func():
>    blahblah...
>
>I find Python's "def is an executable statement" very irritating...

The usual approach is to put all of your other top-level code inside of
a function so that the only executable statements are variable and function
definitions.  This function is often called 'main' and run by the last
bit of code in the file, as in:

def my_func():
    blahblah...

def do_something():
    rutabaga..rutabaga...

def main():
    do_something(my_func)

if __name__ == "__main__":
    main()

As a nice consequence, your file can then be imported as a module
with no additional changes.

There will still be a few occasional problems where you would like
to have references before being defined:

def a(func = b):
  return func("a")

def b(func = a):
  return func("b")

but I've found that they end up being rare.

Hey, here's a cute thought, but I don't recommend you using it:

import sys
class Declare:
  def __init__(self, name):
    self.__name = name
    try:
        1/0
    except ZeroDivisionError:
        self.__globals = sys.exc_info()[2].tb_frame.f_back.f_globals
    self.__globals[name] = self
  def __call__(self, *args, **kw):
    obj = self.__globals[self.__name]
    if obj is self:
        raise NotImplementeError("function %s is undefined" % `self.__name`)
    return apply(obj, args, kw)

>>> def b(func = a):
...    print "I suppose you wanted to say:", func("world")
...
Traceback (innermost last):
  File "<stdin>", line 1, in ?
NameError: a
>>> Declare("a")
<foo.Declare instance at 1201d5460>
>>> def b(func = a):
...    print "I suppose you wanted to say:", func("world")
...
>>> a("world")
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "foo.py", line 13, in __call__
    raise NotImplementedError("function %s undefined" % `self.__name`)
NotImplementedError: function 'a' undefined
>>> b()
I suppose you wanted to say:
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in b
  File "foo.py", line 13, in __call__
    raise NotImplementedError("function %s undefined" % `self.__name`)
NotImplementedError: function 'a' undefined
>>> def a(s):
...     return "Hello, %s!" % s
...
>>> a("world")
'Hello, world!'
>>> b()
I suppose you wanted to say: Hello, world!
>>>

Again, do not use this in your code.  There are more common and appropriate
idioms.

                    Andrew
                    dalke at acm.org






More information about the Python-list mailing list