473,382 Members | 1,252 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

function prototyping?

Hi,

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?

--
burton samograd kruhft .at. gmail
kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com
Apr 13 '06 #1
10 2091
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:

def a():
b()

def b():
print "b called"

a()

So long as you have executed both def statements before you call the first
function it will find the second one. In the example above, if you called
a() before executing 'def b()' the function 'b' wouldn't exist so you
couldn't call it.
Apr 13 '06 #2
Duncan Booth <du**********@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?
--
burton samograd kruhft .at. gmail
kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com
Apr 13 '06 #3
Burton Samograd wrote:
Duncan Booth <du**********@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 'o****@xiludom.gro'.split('@')])"
Apr 13 '06 #4
If you want the user to be able to (re)define them in config.py, why
not just define them there in the first place? I may be wrong, but I
think "global" means "module level" rather than "interpreter level".

Apr 13 '06 #5
"infidel" <sa***********@gmail.com> writes:
If you want the user to be able to (re)define them in config.py, why
not just define them there in the first place? I may be wrong, but I
think "global" means "module level" rather than "interpreter level".


That's what I'm trying to do but I'm running into problems with
the function values, since they haven't been defined yet.

I'm a C programmer, so I'm doing it in a bit of a C like way;
prototype the function, initalize the array using the prototypes, have
the functions defined somewhere else and then let the linker work it
all out for me. I was hoping that python had some sort of lazy
evaluation scheme for this type of behaviour so that you could defer
linkage (or variable evalutation) until runtime, or at least variable
reference (through the use of thunks or some sort). Maybe I was
hoping for too much :)

--
burton samograd kruhft .at. gmail
kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com
Apr 13 '06 #6
bruno at modulix <on***@xiludom.gro> writes:
Burton Samograd wrote:
Duncan Booth <du**********@invalid.invalid> writes:


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


just an example i jotted down, not real code.
'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:


ah yes, that might be a good idea. I'm just hacking together a
prototype right now and I'm thinking in C'isms still, so maybe I'll
modularize it a bit more to see if that could solve the problem.
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.


I like the idea of using python as the configuration system, plus this
is giving me a good exercise with learning more of the language so I'm
going to stick with it for a bit, at least until my questions get too
annoying ;-)
Does python have the idea of a 'weak'
reference


Yes, but that's something totally different.


Care to describe?

--
burton samograd kruhft .at. gmail
kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com
Apr 13 '06 #7
Burton Samograd wrote:
bruno at modulix <on***@xiludom.gro> writes:
(snip)
*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:

ah yes, that might be a good idea. I'm just hacking together a
prototype right now and I'm thinking in C'isms still,


Yeps. Python is easy to get started with, but when it comes to idioms,
it's definitively not C.

(snip)
Does python have the idea of a 'weak'
reference


Yes, but that's something totally different.

Care to describe?


This is in the fine manual. Look for weakref.

Enjoy
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'on***@xiludom.gro'.split('@')])"
Apr 13 '06 #8
Burton Samograd wrote:
"infidel" <sa***********@gmail.com> writes:

If you want the user to be able to (re)define them in config.py, why
not just define them there in the first place? I may be wrong, but I
think "global" means "module level" rather than "interpreter level".

That's what I'm trying to do but I'm running into problems with
the function values, since they haven't been defined yet.

I'm a C programmer, so I'm doing it in a bit of a C like way;
prototype the function, initalize the array using the prototypes, have
the functions defined somewhere else and then let the linker work it
all out for me. I was hoping that python had some sort of lazy
evaluation scheme for this type of behaviour so that you could defer
linkage (or variable evalutation) until runtime, or at least variable
reference (through the use of thunks or some sort). Maybe I was
hoping for too much :)


It's not a problem of "hoping for too much", but a problem of paradigm
shift. You're actually *thinking* in C, and Python is a *completely
different* language. You just can't directly transpose C idioms in
Python - nor could you transpose much Python idioms in C. So you need to
'go down a level' and consider the real problem and how to solve it the
Python way - not how to implement the C-ish solution in Python.
My 2 cents
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Apr 13 '06 #9
Burton Samograd wrote:
Duncan Booth <du**********@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
Apr 13 '06 #10
bruno at modulix <on***@xiludom.gro> writes:
Burton Samograd wrote:
"infidel" <sa***********@gmail.com> writes:
I'm a C programmer, so I'm doing it in a bit of a C like way;
prototype the function, initalize the array using the prototypes, have
the functions defined somewhere else and then let the linker work it
all out for me. I was hoping that python had some sort of lazy
evaluation scheme for this type of behaviour so that you could defer
linkage (or variable evalutation) until runtime, or at least variable
reference (through the use of thunks or some sort). Maybe I was
hoping for too much :)


It's not a problem of "hoping for too much", but a problem of paradigm
shift. You're actually *thinking* in C, and Python is a *completely
different* language. You just can't directly transpose C idioms in
Python - nor could you transpose much Python idioms in C. So you need to
'go down a level' and consider the real problem and how to solve it the
Python way - not how to implement the C-ish solution in Python.


To be honest, I'm trying to do it in a more 'lispish' way (as in emacs
lisp) where the configuration file is written in the implementation
langugage. Just an interesting experiement really to see if it would
work. It's been a year and a half since I really used python last so
I'm just getting back up to speed with the idioms so I expect to make
a few mistakes along the way.

Thanks for the help.

--
burton samograd kruhft .at. gmail
kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com
Apr 13 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

30
by: Dave Allison | last post by:
Oh no, not another "check out my cool new language" posting :-) For about 5 years now, I have been developing a scripting/prototyping language that is now available on the net. It's called...
9
by: Carl | last post by:
I have been using Python for quite some time now and I love it. I use it mainly for explorative computing and numerical prototyping, ie testing and trying out different kinds of algorithms and...
1
by: Richard A. DeVenezia | last post by:
foo() generates elements with event handlers that invoke foo function properties. Is this an abhorrent or misthought pattern ? It allows just the one occurence of identifier /foo/ to be changed...
4
by: Jeff Thies | last post by:
It seems to me that document.getElementById and document.all are essentially the same thing. I'm thinking of prototyping document.getElementById for those browsers that understand document.all...
2
by: Martin McCormick | last post by:
Most of the C programming I write manipulates strings so I haven't had much experience with numerical functions and passing variables in and out which brings me to a laughably simple problem that I...
13
by: rs | last post by:
Dear All, I have a question regarding proptypes for functions. What is the recommended practice? The way I do it is to put all my external functions in a header file, while protyping...
4
by: Tilted | last post by:
Does anyone here use prototyping tools? I'm building one myself as I feel like I'm doing the same thing over and over again with the majority of my projects, how do people generally feel about...
5
by: jeremito | last post by:
I am extending python with C++ and need some help. I would like to convert a string to a mathematical function and then make this a C++ function. My C++ code would then refer to this function to...
25
by: hifrnds007 | last post by:
how the function poiners avoids the usage of switch cases?
8
by: vaib | last post by:
hi all , It really seems that C never ceases to amaze . All this time i've been doing C and i thought i was quite adept at it but i was wrong . So without wasting any more time , here's the...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.