adding attributes to a function, from within the function

Werner Schiendl ws-news at gmx.at
Fri Oct 31 11:49:40 EST 2003


Hi,

Fernando Rodriguez wrote:

> 
> I'd like to do something like this:
> 
> def fn():
>   error = "Error message"
>   return 1
> 
> print fn.error
> 

AFAIK, not at all.

The reason is, that in Python the function definition is an executable
statement and therefore the function does not exist until after it's
end.

So you can either stay with your first approach, which should be fine
as long as you always assign a static string.

However, your code makes me believe you want to provide error details to 
a caller in case something goes awry. The proper way to handle errors in 
Python, however, is to use exceptions - not return values.

for example:

 >>> class MyException(Exception):
... 	def __init__(self, details):
... 		self.details = details
... 		
 >>> def f(x):
... 	if x < 0:
... 		raise MyException("x must not be negative")
... 	# do normal processing
... 	
 >>> try:
... 	f(-1)
... except MyException, e:
... 	print "Something went awry:", e.details
... 	
Something went awry: x must not be negative


hth

Werner






More information about the Python-list mailing list