comments? storing a function in an object

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Jul 21 00:31:04 EDT 2009


En Mon, 20 Jul 2009 22:53:59 -0300, Esmail <ebonak at hotmail.com> escribió:

> Gabriel Genellina wrote:
>  >
>> If you follow the above suggestions, you'll see that your Function  
>> class becomes almost useless: a normal function already IS an object,  
>> so you don't have to wrap it inside ANOTHER object unless you need very  
>> special features.
>
> Hello Gabriel,
>
> In general I would agree with you, but in my specific case
> I want so store some additional meta-data with each function, such
> as the valid range for input values, where the max or minimum are  
> located,
> the name/source for the function etc. I am creating list of functions
> for use in testing optimization code, so it seems best to store this
> data along with the function I am going to optimize in order to verify
> the results for a given range (for instance).

You can store all meta-data in the function itself:

py> def triangle(b, h):
...   "area of triangle: b*h/2"
...   return b*h/2
...
py> triangle.foo = "some value"
py> triangle.foo
'some value'

Python already knows some properties:

py> triangle.func_code.co_argcount
2
py> triangle.func_doc
'area of triangle: b*h/2'
py> triangle.__doc__
'area of triangle: b*h/2'

You may use this variant of Carl Banks proposal - this is a factory  
function that returns new function objects:

def inline_function_factory(name, args, expr):
   ns = {}
   exec '''def %s(%s):
             %r
             return %s''' % (
     name, args, expr, expr) in ns
   function = ns[name]
   return function

py> sqr = inline_function_factory("square", "x", "x*x")
py> sqr(3)
9
py> sqr.__doc__
'x*x'
py> sqr
<function square at 0x00B46770>

Wrapping a function object isn't necesarily bad, but perhaps you're doing  
things more complicated than should be.

-- 
Gabriel Genellina




More information about the Python-list mailing list