473,406 Members | 2,705 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

adding attributes to a function, from within the function

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
Jul 18 '05 #1
6 2130
> 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. :)
Jul 18 '05 #2
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
Jul 18 '05 #3
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

Jul 18 '05 #4
Hi,

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

kk = fn()
kk.error
'Error message'

-shuhsien
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


Jul 18 '05 #5
Shu-Hsien Sheu <sh**@bu.edu> wrote in message news:<ma************************************@pytho n.org>...
I think you would need to use a class rather than function.
>>> class fn(object): def __init__(self):
self.error = 'Error message'

>>> kk = fn()
>>> kk.error

'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
Jul 18 '05 #6
Fernando Rodriguez <fr*@easyjob.net> wrote in message news:<as********************************@4ax.com>. ..
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
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Francis Avila | last post by:
A little annoyed one day that I couldn't use the statefulness of generators as "resumable functions", I came across Hettinger's PEP 288 (http://www.python.org/peps/pep-0288.html, still listed as...
2
by: Paul Dunstone | last post by:
Hi group I am trying to add a custom attribute to all .NET elements such as textboxes, labels, datagrids etc. I want to add an attribute called 'key'. I already have the code working for the...
15
by: crjunk | last post by:
I have 4 TextBoxes on my form that I'm trying to add together to get a grand total. Here is the code I'm using: <SCRIPT LANGUAGE="JavaScript"> <!-- Beginning of JavaScript - function...
4
by: Craig G | last post by:
i was using the following on a serverside button on a form If (Not Page.IsPostBack) Then Me.BtnDelete.Attributes.Add("onclick","return confirm('Are you sure you want to delete?');") End If ...
3
by: J'son | last post by:
Guys, I have created a custom class that derives from DataList so that I can add some custom client side functionality into each new item row (<td>). Heres the class in its simplest form: ...
28
by: Ilias Lazaridis | last post by:
I understand that I can use __metaclass__ to create a class which modifies the behaviour of another class. How can I add this metaclass to *all* classes in the system? (In ruby I would alter...
5
by: Nathan Harmston | last post by:
Hi, Sorry if the subject line of post is wrong, but I think that is what this is called. I want to create objects with class Coconuts(object): def __init__(self, a, b, *args, **kwargs):...
1
by: ton | last post by:
Hi, I want to add several textbox to my form during runtime: the code is very simple Lab = New TextBox Lab.ID = "A" & i Lab.Height = 200 Lab.Visible = True Lab.Text = "test"
11
by: Rafe | last post by:
Hi, I'm working within an application (making a lot of wrappers), but the application is not case sensitive. For example, Typing obj.name, obj.Name, or even object.naMe is all fine (as far as...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.