too simple a question : forward declaration?

Alex Martelli aleax at aleax.it
Wed May 14 07:47:12 EDT 2003


Helmut Jarausch wrote:
   ...
>> You cannot.  Python has no declarations, just
>> executable statements.  Having no declarations,
>> it has, in particular, no FORWARD declarations.
> 
> This argument is not a forcing one. I know
> Python fans are tired of comparisons with Perl
> but here Perl does have, as well as Python, FUNCTION
> declarations.

Python doesn't.  'def' is not a declaration: it is
an executable statement just like any other.  E.g.:

def makefuns():
    result = []
    for i in range(5):
        def afunc(x=i):
            print x
        result.append(afunc)
    return result

How could you possibly explain this function's
behavior if 'def' was a ``declaration''...???  def
is an executable statement: when it executes (and
it can be in a loop, in an if, etc etc, just like any
other executable statement) it creates a function
object and binds a name to the object it creates.

Forget the existence of 'declarations' in other
languages.  In Python they do not exist (the 'global'
statement comes closest, but it has nothing to do
with the 'declaration of functions' anyway).

> In Perl one can say, e.g.
> use subs qw/....../;
> 
> or just
> sub myfunc(<Parameterlist>);
> i.e. without a function body

That's an indication that this 'sub' is a declaration:
it doesn't DO anything, and I doubt you can significantly
put it in an if statement or a loop.  'def' is totally
different and you're doing yourself a disservice if
you persist in denying this fact.



> Yes, I thought about that, but in my C++ courses I always
> mention the example of two (recursive) functions calling
> each other.
> So, how is this impossible in Python ?

It's not impossible at all, why should it be?

def sillyone(n):
    print 'one!'
    if n>0:
       sillytwo(n-1)

def sillytwo(n):
    print 'two!'
    sillyone(n)

sillyone(6)

The BODY of function sillyone is executed after the *def*
statement that binds name 'sillytwo' in global scope, so
when said body executes global name sillytwo is bound and
the mutually recursive calls work without a hitch.

> Are there cyclically dependent import statements
> allowed?

Yes, although like any ciclic dependency between separate
units they're a disaster more often than not, hardly ever
do what one might naively expect, and are well worth going
out of your way to avoid (I recommend the works of Lakos
and Robert "Uncle Bob" Martin on dependency control and
avoidance, since you mentioned you're familiar with C++).

See section "Circular Imports" in the Nutshell's Chapter 7,
"Modules", p. 122-123, for a concise explanation of some
issues that arise when doing circular imports.


Alex





More information about the Python-list mailing list