function prototyping?
Peter Otten
__peter__ at web.de
Thu Apr 13 15:13:56 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 = {
> '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
>
> import config
> def main():
> config.dict['a']()
> config.dict['b']()
> main()
> --------------------------------------
>
> 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. Does python have the idea of a 'weak'
> reference or lazy style evaluation for the definition of the dict in
> the config file above so I can achive what i'm tryin to do?
I'd say Python has *only* that idea, but as a practical approach the
following might be easiest:
-- config.py --
a = a_fun # As a_fun is nowhere defined, config.py cannot be
# used stand-alone and may be hard to test.
b = b_fun
def c():
print "c-fun"
-- fun.py --
def a_fun(): print "a-fun"
def b_fun(): print "b-fun"
execfile("config.py") # Think #include <config.py>
def main():
a()
b()
c()
if __name__ == "__main__":
main()
A slightly stricter variant avoids cycles by using three modules:
-- fun.py --
def a_fun(): print "a-fun"
def b_fun(): print "b-fun"
-- config.py --
import fun
a = fun.a_fun
b = fun.b_fun
-- main.py --
import config
def main():
config.a()
config.b()
if __name__ == "__main__":
main()
Thanks to the if... guard you could put the main.py code into fun.py, too,
but I suppose it's easier to understand with three files.
Peter
More information about the Python-list
mailing list