function prototyping?

bruno at modulix onurb at xiludom.gro
Thu Apr 13 14:25:44 EDT 2006


Burton Samograd wrote:
> Duncan Booth <duncan.booth at invalid.invalid> writes:
> 
> 
>>Burton Samograd wrote:
>>
>>>Is there any way to 'prototype' functions in python, as you would in
>>>C?  Would that be what the 'global' keyword is for, or is there a more
>>>elegant or 'pythonic' way of doing forward references?
>>>
>>
>>There isn't really such a thing as a forward reference in Python. Always 
>>remember that 'def' and 'class' are executable statements:
> 
> 
> Ok, we'll here's what I'm trying to do.  I have a dictionary that I
> would like to initialize in a module file config.py:
> 
> -- config.py -------------------------
> global a_fun, b_fun
> dict = {

dont use 'dict' as an identifier, it shadows the builtin dict type.

> 'a': a_fun,
> 'b': b_fun
> } 
> --------------------------------------
> 
> where a_fun and b_fun are in fun.py:
> 
> -- fun.py ----------------------------
> def a_fun(): pass
> def b_fun(): pass

Until this point, everything is (almost) fine. You'd just need to
rewrite config.py so it imports a_fun and b_fun from fun.py:

#-- config.py -------------------------
import fun
conf = {
 'a': fun.a_fun,
 'b': fun.b_fun
}
# --------------------------------------

But then, we have this :

> import config

And then we have a circular import...

*But* is it necessary to have the main() in the same file that defines
a_fun and b_fun ? It's quite common (and not only in Python) to use a
distinct file for the main(). So you can easily solve your problem by
splitting fun.py into fun.py and main.py:

#-- main.py -------------------------
import config
def main(*args):
    config.dict['a']()
    config.dict['b']()

# here we have a python trick:
if __name__ == '__main__':
    import sys
    sys.exit(main(*sys.argv[1:])
# --------------------------------------


> I like having the module/namespace seperation with the configuration
> variables but I would like to make them easily (re)defined in the
> configuration file by the user.

You may want to look at one of the existing configuration modules.

>  Does python have the idea of a 'weak'
> reference

Yes, but that's something totally different.

(snip)

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list