adding attributes to a function, from within the function

F

Fernando Rodriguez

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"
return 1

print fn.error

How can I do this? O:)

TIA
 
S

Sean Cody

What's the syntax to add an attribute to a function form the function
body?I don't think this is entirely possible as there is no way obvious way to
introspect the members of a function based on the language (as I know it).

Functions can be invoked many times so you would not know which version of
the member variable you will get (assuming the python interpeter copies the
text segment of the function instead of branching to it [which is probably
the case and if so the text segment doesn't normally have 'user memory'
allocated within it as local variables may be on the stack [unless in python
even local statics are heap based]]). Once a function has finished its
memory is free'd unless it is some sort of static function.

What you could do is:

class fn:
__init__():
self.error = -1
function_stuff()

Then you could do it but it is more effort that it is worth...

From an OO or even modular standpoint you shouldn't break scope unless there
is a really good reason to.

--
Sean
P.S. I'm probably totally wrong but if I didn't at least try I wouldn't
learn anything. :p
P.P.S. I've used way too many buzz words.... maybe I shouldn't post to
groups shortly after management meetings. :)
 
W

Werner Schiendl

Hi,

Fernando said:
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:
.... def __init__(self, details):
.... self.details = details
.... .... if x < 0:
.... raise MyException("x must not be negative")
.... # do normal processing
.... .... f(-1)
.... except MyException, e:
.... print "Something went awry:", e.details
....
Something went awry: x must not be negative


hth

Werner
 
S

Shu-Hsien Sheu

Hi,

I think you would need to use a class rather than function.
def __init__(self):
self.error = 'Error message'

'Error message'

-shuhsien
 
A

Alex Martelli

Fernando said:
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
 
H

Hung Jung Lu

Shu-Hsien Sheu said:
I think you would need to use a class rather than function.

def __init__(self):
self.error = 'Error message'


'Error message'

Yes, in Python it's more natural to use a class object for storing
attributes. What the original poster wanted was some sort of
"closure-like" function, that is, a function object that can carry
some data member as well. Also, in C++, you have static variables
inside functions. In Python, if you use a function object, you can't
insert attributes during the definition of the function.

In Python, an class instance can be made callable by implementing the
__call__() method. If the function is supposed to be singleton, then
you can use:

class fn(object):
error = 'Error message'
def __call__(self, x=None):
if x is None:
return 1
else:
return 2*x
fn = fn() # gets rid of the class, this makes fn singleton
print fn() # prints 1
print fn(3) # prints 3
print fn.error # prints 'Error message'

regards,

Hung Jung
 
M

Michele Simionato

Fernando Rodriguez said:
Hi,
I'd like to do something like this:

def fn():
error = "Error message"
return 1

print fn.error

You can always use a closure:

def function_with_error_message(error):
def _(): return 1
_.error=error
return _

fn=function_with_error_message("Error message")
print fn.error

However, IMHO using a class is better since automatic
documentation tools and inspection features work better for classes
than for closures.

Michele
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top