473,770 Members | 1,952 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Invisible function attributes

Python 2.3
def foo(): .... foo.a = 1
.... vars(foo) {} foo()
vars(foo) {'a': 1}


So it would appear that function attributes are not really
there until the first call to the function. If that is the
intended behaviour, it is really weird. I couldn't find any
explicit discussion of this topic in the LRM.

Thanks if anyone can shed some light on this,

-- O.L.
Jul 18 '05 #1
10 2320
Olivier Lefevre wrote:
Python 2.3
def foo():
... foo.a = 1
...
vars(foo)
{}
foo()
vars(foo)


{'a': 1}
So it would appear that function attributes are not really
there until the first call to the function. If that is the
intended behaviour, it is really weird. I couldn't find any
explicit discussion of this topic in the LRM.

Thanks if anyone can shed some light on this,

-- O.L.


Makes sense to me.

The foo.a = 1 line should never be executed until foo() is executed.
Thus, foo.a is never set before the call to foo.

- TL

Jul 18 '05 #2
def foo():
try:
foo.a += 1 # executed every time you call the function
except AttributeError:
foo.a = 1 # set to one if it's not already there

foo.b = 1 # executed once

print vars(foo) # function body not yet called {'b': 1}

for i in range(3):
foo()
print vars(foo)

Loop output is

{'a': 1, 'b': 1}
{'a': 2, 'b': 1}
{'a': 3, 'b': 1}

That is all perfectly sane as code in the function body is never executed
unless you call the function, whereas code on the module level is executed
immediately as the module is imported. So put foo.attr = ... into the
function body iff you want it to execute every time the function is
invoked; otherwise put it into the module startup code, i. e. do not indent
it.

Peter

Jul 18 '05 #3

"Olivier Lefevre" <le******@yahoo .com> wrote in message
news:51******** *************** ***@posting.goo gle.com...
Python 2.3
def foo(): ... foo.a = 1


If you want foo to be attributed before it is called, move the setter
outside the function.
def foo(): pass .... foo.a = 1
vars(foo)

{'a': 1}

Terry J Reedy
Jul 18 '05 #4
le******@yahoo. com (Olivier Lefevre) writes:
[...]
So it would appear that function attributes are not really
there until the first call to the function. If that is the
Not function attributes in general, just those that are first assigned
to in the function body. No special rule here, though, because...

intended behaviour, it is really weird. I couldn't find any
explicit discussion of this topic in the LRM.

Thanks if anyone can shed some light on this,


....what I'm guessing you haven't figured out yet is that everything
works like this in Python. For example, what might be called a 'class
declaration' in other languages isn't really a declaration in Python,
it's code that gets executed at runtime. Same is true of functions:

if WANT_SPAM:
def sayhello(): print "spam"
else:
def sayhello(): print "eggs"

sayhello()
And your foo.a = 1 isn't a declaration (Python doesn't have them,
really), it's just an attribute assignment.
John
Jul 18 '05 #5
Thanks to all those who replied.
...what I'm guessing you haven't figured out yet is that everything
works like this in Python.


Very possibly. I am coming to python from Java and I want to investigate
the weird stuff precisely because either it's a one-off (in which case
I'll make a note to myself to ignore it and not use it) or it holds the
key to what is specific about the language. I seem to have hit pay dirt
with this one ;-)

Nudged by the dot syntax, I was thinking of this function attribute as
if it were a sort of class member (i.e., pretending for a while this
function is a class) and, since functions can't have instances, treating
it as a sort of static member of the function, which should be available
as soon as declared. Obviously I got it all wrong. Instead, they work
like local variables except that they "persist" after the function has
exited. That still feels weird to me. What are they used for? Give me
a compelling reason to have such a beast in the language.

OTOH, does this behaviour have anything to do with so-called "futures"?

-- O.L.
Jul 18 '05 #6

"Olivier Lefevre" <le******@yahoo .com> wrote in message
news:51******** *************** ***@posting.goo gle.com...
Thanks to all those who replied.
...what I'm guessing you haven't figured out yet is that everything
works like this in Python.
Very possibly. I am coming to python from Java and I want to investigate
the weird stuff precisely because either it's a one-off (in which case
I'll make a note to myself to ignore it and not use it) or it holds the
key to what is specific about the language. I seem to have hit pay dirt
with this one ;-)

Nudged by the dot syntax, I was thinking of this function attribute as
if it were a sort of class member (i.e., pretending for a while this
function is a class) and, since functions can't have instances, treating
it as a sort of static member of the function, which should be available
as soon as declared. Obviously I got it all wrong. Instead, they work
like local variables except that they "persist" after the function has
exited. That still feels weird to me. What are they used for? Give me
a compelling reason to have such a beast in the language.


I don't know of a really compelling reason, other than it simply
works that way. Like everything else in the language, functions
are objects, which means that they have a dictionary at their
core. Therefore, functions can have attributes.

The only use I can think of would be definitely advanced
programming. Functions are first class objects, which means
they can be rebound anywhere you want them. If you find
a good reason to do that, then as an extension you might find
a reason to add attributes to classify what you've got so you
can manage the process.

As I said, I'm reaching with this one...

OTOH, does this behaviour have anything to do with so-called "futures"?
No. Future is a feature so that experimental features can be added to the
language in one release, and then made standard in a future release.

John Roth
-- O.L.

Jul 18 '05 #7
Of course the inevitable question is why do you want to do this? Consider
creating a class instead (with a __call__ method if you want to call the
instance as a function).

class Foo:
a = 1 # pre-initialized property
def __call__(self):
print self.a

foo = Foo()
foo()
# prints 1

Bob Gailer
bg*****@alum.rp i.edu
303 442 2625
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003

Jul 18 '05 #8
le******@yahoo. com (Olivier Lefevre) writes:
Nudged by the dot syntax, I was thinking of this function attribute as
if it were a sort of class member (i.e., pretending for a while this
function is a class) and, since functions can't have instances, treating
it as a sort of static member of the function, which should be available
as soon as declared.
There is no declaration in Python; you just create attributes by
binding objects to names.
Obviously I got it all wrong. Instead, they work like local
variables except that they "persist" after the function has exited.
Hmmm. No. Functions are first class objects, and you can dynamically
add attributes to them as you go along (as is the case for many, but
not all, other types of objects).

Do you realize that the foo identifier you used in your example is not
inextricably linked to any function whose name is foo? The name of a
function, and the variables to which it is bound are two different
concepts.

Consequently, the foo.a in the function body only _coincidentally _
refers to an attribute of the function in which it appears.

Consider:
def foo(arg): foo.a = arg .... bar = foo # Now the function is known by two different names
bar(3)
foo.a 3 foo = 1 # Now the function called "foo" can only be accessed via bar !
bar(4) Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in foo
TypeError: 'int' object has only read-only attributes (assign to .a) bar # I call it "bar", bit it thinks it's called "foo" <function foo at 0x815e71c>


The error at "bar(4)" in the above should hint at the fact that the
"foo" in "foo.a" in the definition of the function foo, does not refer
to the function itself but to whatever object which happens to be
bound to the name "foo" at the time the function is being exectuted.
What are they used for? Give me a compelling reason to have such a
beast in the language.


Now there's a good question :-) I haven't found a use for these
myself ... but then I haven't looked very hard for one.

Given that function attributes were added to the language (in version
2.1 or 2.2 ?), I guess someone felt a need for them, and Guido agreed.
Jul 18 '05 #9
> Python has no declarations, only executable statements.

I think this was the key to my confusion in this case.
bar(4)

Traceback (most recent call last):
TypeError: 'int' object has only read-only attributes (assign to .a)


The way I read this, it says that a was bound to the name foo,
not to the function foo stood for at the time of that function's
definition; you are saying as much. Thus "foo.a" has to be looked
up and resolved anew for each call. This must be costly. Why was
it done this way?

OTOH I read the func attr PEP and it says that they are
implemented via a dict inside the function object. If so,
shouldn't they be bound to the function object rather than
to its name?? Or is func_dict itself an attribute?

-- O.L.
Jul 18 '05 #10

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

Similar topics

11
2030
by: Saqib Ali | last post by:
Please excuse me, this is a fairly involved question that will likely require you to save the file below to a file and open it in a browser. I use Mozilla 1.5, so the problem I describe below should be reproducible with that version at least. BACKGROUND: =========== When you open this page in your browser, you will see a 4 cell table. The cells contain the following items respectively:
5
8225
by: Harry Gould | last post by:
To all, I'm a newbie here, so please bear with me. I develop web pages for a company intranet where Internet Explorer 6 is the standard. Now I must develop a public internet website that is browser-agnostic (i.e., works with Netscape, version 4x, 7x, etc). My question is this: I have about 10 table rows, each tagged with a class attribute (<tr class="billing" style="display:none">) that I wish to make visible or invisible in response...
67
6050
by: Sandy.Pittendrigh | last post by:
Here's a question I don't know the answer to: I have a friend who makes very expensive, hand-made bamboo flyrods. He's widely recognized (in the fishing industry) as one of the 3-5 'best' rod makers in the world. He gets (sic) close to $5000 per custom made flyrod. A surprising number of people buy these fishing rods and never use them....they buy them as art-like investments. He is, after all, the best there is. But if you search on...
6
14699
by: Selden McCabe | last post by:
I have a form with a bunch of image buttons. When the user moves the mouse over a button, I want to do two things: 1. change the Imagebutton's picture, and 2. make another control visible. I'm using the Imagebutton.Attributes.Add("onMouseOver","this.src = 'somepicture.jpg') and that works fine. I've tried some java script to change the other control's visible property by changing is className, but that doesn't seem to work
1
4543
by: Graham Charles | last post by:
I'm trying to create a standard "hidden" table. However, using this code, my tables are not displayed in the database window *even* when I choose to show Hidden and System objects from the Options dialog: tdf = theDB.CreateTableDef(OptionsTableName) fld = tdf.CreateField("OptionName", dao.DataTypeEnum.dbText, 50) tdf.Fields.Append(fld)
0
1152
by: COHENMARVIN | last post by:
I have a page that has a menu running down the left side. When I load a wide gridview into the page, that gridview doesn't fit to the right of the menu. So it gets moved below the menu. I tried making the menu invisible, but the gridview still appears way down on the page. I can't get rid of the menu, or move it somewhere else, because the program I'm working on belongs to my company and they want it on the left side. Is there some...
2
1264
by: lanmind | last post by:
Hello, I have a PHP script that returns a PHP variable's value (a number in this case) inside an XML document to the client. Is it possible to make this number invisible when the user views the returned XML but still accessible by some javascript? Thank you
1
6473
by: Beamor | last post by:
function art_menu_xml_parcer($content, $showSubMenus) { $doc = new DOMDocument(); $doc->loadXML($content);//this is the line in question $parent = $doc->documentElement; $elements = $parent->childNodes; need help. my site worked fine on my localhost but when i uploaded it to my live server i keep getting this error need help to recode line to match my hosting server. im using php 5 i have attached the common_method file
0
9617
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10099
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9904
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8929
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6710
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5481
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3607
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2849
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.