[Zope] Re: python script get defined function by name

Lee Harr missive@hotmail.com
Thu, 17 Oct 2002 01:58:53 +0000


>Lee Harr wrote:
>>If I define a function inside a PythonScript, can I get that
>>function by name somehow using getattr() or some other way?
>>
>>As in...
>>
>>#PythonScript
>>
>>def abc():
>>  pass
>>
>>abc = getattr(======, 'abc')
>
>In Python, a 'def' statement binds the newly created function to a name in 
>the current namespace.  Your definition acts a little bit like the (totally 
>imaginary) code:
>
>abc = make_function('abc', (), 'pass')
>
>...so 'abc' already exists, there's no need to "get" it.
>
>Example:
>
>def abc(x):
>   return x + 1
>
>y = abc(1)
>


Sorry, that was a typo. Should have been:

f = getattr(======, 'abc')

as in:

# PythonScript
# parameters:
#   whichFunction='abc'

def abc():
  return 'this is abc'

def cba():
  return 'this is bca'

f = getattr(======, whichFunction)

return f()

# end

If I do not know which function I want to run until
runtime, then I cannot use the function handle, I
need to "get" the function by name.


Now, I have worked around this problem by defining
abc and bac as PythonScripts in the same folder as
the original one, then I can use:

f = getattr(container, whichFunction)

but that is a bit of a hassle if I have a few very
simple functions and just want to choose one by name.


hmm... now that I think about it, I could also say:

funcs = {'abc': abc, 'cba': cba}
f = funcs[whichFunction]

but it seems like there is probably a very simple
handle for the current PythonScript namespace, and
I just dont know what it is.


Thanks for your help.


_________________________________________________________________
Protect your PC - get McAfee.com VirusScan Online 
http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963