adding attributes to a function, from within the function

Alex Martelli aleax at aleax.it
Fri Oct 31 12:24:45 EST 2003


Fernando Rodriguez wrote:

> Hi,
> 
> What's the syntax to add an attribute to a function form the function
> body?
> 
> For example, instead of doing:
> def fn():
>    return 1
> fn.error = "Error message"
> print fn.error
> 
> 
> I'd like to do something like this:
> 
> def fn():
>   error = "Error message"

nope, that would be a local variable of the function

>   return 1
> 
> print fn.error
> 
> How can I do this? O:-)

by assigning to fn.error within the function body you can
approximate this, BUT, the function body will of course not
be executed until the function is CALLED, so, given that in
your "like to do" you're not calling it, there is NO way it
can ever get your desiderata (access something that WOULD
be set if you called the function, WITHOUT calling it).


Alex





More information about the Python-list mailing list