Python dynamic function selection

Daniel 'Dang' Griffith noemail at noemail4u.com
Wed May 12 11:02:33 EDT 2004


On 12 May 2004 01:42:02 -0700, ekoome at yahoo.com (Eric) wrote:

>The following example will explain what i want to do:
>>>> def func():
>	print "true"
>>>> rules=(func,)
>>>> for rule in rules:
>        rule
>
>I expect the final function to print true, but instead i have
><function func at 0x00DC6EB0>
>
>How do i get it to print true. I know if i had parameters in rule
>like:
>>>> def func(var):
>	print var
>>>> rules=(func,)
>>>> for rule in rules:
>        rule("true")
>it will work. But in my case i don't need to pass any parameters.
>
>How do i get the former method to print instead of returning a
>function?

In Python, as in C and many other languages (but not BASIC or
Pascal/Delphi and probably others), to call/invoke/execute a function,
you need to put parentheses after the name.  This is what the others'
examples have shown:
    for rule in rules:
        rules() # call the function
If this were not the way it worked, then in the line above it, where
you have:
    rules=(func,)
it would have (called and) printed true and returned None
(implicitly), and rules would point to a (None,) tuple.

    --dang



More information about the Python-list mailing list