I defined a nested function:
def foo():
def bar():
return "bar"
return "foo " + bar()
which works. Knowing how Python loves namespaces, I thought I could do
this:
>>foo.bar()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'function' object has no attribute 'bar'
but it doesn't work as I expected.
where do nested functions live? How can you access them, for example, to
read their doc strings?
--
Steven. 23 1953
Steven D'Aprano wrote:
I defined a nested function:
def foo():
def bar():
return "bar"
return "foo " + bar()
which works. Knowing how Python loves namespaces, I thought I could do
this:
>>>foo.bar()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'function' object has no attribute 'bar'
but it doesn't work as I expected.
where do nested functions live?
in the local variable of an executing function, just like the variable
"bar" in the following function:
def foo():
bar = "who am I? where do I live?"
(yes, an inner function is *created* every time you execute the outer
function. but it's created from prefabricated parts, so that's not a
very expensive process).
</F>
"Steven D'Aprano" <st***@REMOVE.T HIS.cybersource .com.auwrites:
I defined a nested function:
def foo():
def bar():
return "bar"
return "foo " + bar()
which works. Knowing how Python loves namespaces, I thought I could
do this:
>foo.bar()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'function' object has no attribute 'bar'
but it doesn't work as I expected.
Functions don't get attributes automatically added to them the way
class do. The main exception is the '__doc__' attribute, referring to
the doc string value.
where do nested functions live?
They live inside the scope of the function. Inaccessible from outside,
which is as it should be. Functions interact with the outside world
through a tightly-defined interface, defined by their input parameters
and their return value.
How can you access them, for example, to read their doc strings?
If you want something that can be called *and* define its attributes,
you want something more complex than the default function type. Define
a class that has a '__call__' attribute, make an instance of that, and
you'll be able to access attributes and call it like a function.
--
\ "Writing a book is like washing an elephant: there no good |
`\ place to begin or end, and it's hard to keep track of what |
_o__) you've already covered." -- Anonymous |
Ben Finney
Steven D'Aprano wrote:
I defined a nested function:
def foo():
def bar():
return "bar"
return "foo " + bar()
which works. Knowing how Python loves namespaces, I thought I could do
this:
>>>>foo.bar()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'function' object has no attribute 'bar'
but it doesn't work as I expected.
where do nested functions live? How can you access them, for example, to
read their doc strings?
It doesn't "live" anywhere: if I wrote the function
def foo():
locvar = 23
return locvar
would you expect to be able to access foo.locvar?
It's exactly the same thing: the statement
def bar():
isn't executed until the foo() function is called, and its execution
binds the name bar in foo's local namespace to the function that is defined.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
Ben Finney wrote:
If you want something that can be called *and* define its attributes,
you want something more complex than the default function type. Define
a class that has a '__call__' attribute, make an instance of that, and
you'll be able to access attributes and call it like a function.
I turned Steven's question and portions of the answers into a Python FAQ
entry: http://effbot.org/pyfaq/where-do-nes...tions-live.htm
Hope none of the contributors mind.
</F>
On Sat, 28 Oct 2006 09:59:29 +0200, Fredrik Lundh wrote:
>where do nested functions live?
in the local variable of an executing function, just like the variable
"bar" in the following function:
def foo():
bar = "who am I? where do I live?"
(yes, an inner function is *created* every time you execute the outer
function. but it's created from prefabricated parts, so that's not a
very expensive process).
Does this mean I'm wasting my time writing doc strings for nested
functions? If there is no way of accessing them externally, should I make
them mere # comments?
--
Steven.
In <pa************ *************** *@REMOVE.THIS.c ybersource.com. au>, Steven
D'Aprano wrote:
Does this mean I'm wasting my time writing doc strings for nested
functions? If there is no way of accessing them externally, should I make
them mere # comments?
Whats the difference in "wasted time" between using """ or # as delimiters
for the explanation what the function is doing!? Or do you ask if you
should not document inner functions at all? Someone might read the source
and be very happy to find docs(trings) there.
And of course there are inner functions that are returned from the outer
one and on those objects it is possible to inspect and read the docs.
Ciao,
Marc 'BlackJack' Rintsch
Fredrik Lundh wrote:
Ben Finney wrote:
>If you want something that can be called *and* define its attributes, you want something more complex than the default function type. Define a class that has a '__call__' attribute, make an instance of that, and you'll be able to access attributes and call it like a function.
I turned Steven's question and portions of the answers into a Python FAQ
entry:
http://effbot.org/pyfaq/where-do-nes...tions-live.htm
Hope none of the contributors mind.
I'd add that while in some respect "def x" is like
an assigment to x ...
>>def f():
global g
def g():
return "Yoo!"
>>f() g()
'Yoo!'
in some other respect (unfortunately) it's not a regular assignment
>>x = object() def x.g():
SyntaxError: invalid syntax
>>>
Andrea
Fredrik Lundh wrote:
Steven D'Aprano wrote:
>I defined a nested function:
def foo(): def bar(): return "bar" return "foo " + bar()
which works. Knowing how Python loves namespaces, I thought I could do this:
>>>>foo.bar() >
Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError : 'function' object has no attribute 'bar'
but it doesn't work as I expected.
where do nested functions live?
in the local variable of an executing function, just like the variable
"bar" in the following function:
def foo():
bar = "who am I? where do I live?"
(yes, an inner function is *created* every time you execute the outer
function. but it's created from prefabricated parts, so that's not a
very expensive process).
</F>
If I may turn the issue around, I could see a need for an inner function
to be able to access the variables of the outer function, the same way a
function can access globals. Why? Because inner functions serve to
de-multiply code segments one would otherwise need to repeat or to
provide a code segment with a name suggestive of its function. In either
case the code segment moved to the inner function loses contact with its
environment, which rather mitigates its benefit.
If I have an inner function that operates on quite a few outer
variables it would be both convenient and surely more efficient, if I
could start the inner function with a declaration analogous to a
declaration of globals, listing the outer variables which I wish to
remain writable directly.
I guess I could put the outer variables into a list as argument to
the inner function. But while this relieves the inner function of
returning lots of values it burdens the outer function with handling the
list which it wouldn't otherwise need.
Frederic
If I may turn the issue around, I could see a need for an inner function
to be able to access the variables of the outer function, the same way a
function can access globals. Why? Because inner functions serve to
de-multiply code segments one would otherwise need to repeat or to
provide a code segment with a name suggestive of its function. In either
case the code segment moved to the inner function loses contact with its
environment, which rather mitigates its benefit.
Maybe I'm dense here, but where is your point? Python has nested lexical
scoping, and while some people complain about it's actual semantics, it
works very well:
def outer():
outer_var = 10
def inner():
return outer_var * 20
return inner
print outer()()
Diez This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Andy Baker |
last post by:
Hi there,
I'm learning Python at the moment and trying to grok the thinking behind
it's scoping and nesting rules.
I was googling for nested functions and found this Guido quote:
(http://www.python.org/search/hypermail/python-1993/0343.html)
"This is because nested function definitions don't have access to the
local variables of the surrounding block -- only to the globals of the
|
by: A |
last post by:
Hi,
How do you make use of nested functions in C++? I realize in C++ that
everything must be declared first in a header file before implementation in
a .cpp file. I tried to nest a method prototype in another prototype but
seems pointless. Can someone please write a short, simple, and concise
skeleton code of how to use nested functions?
class Foo
{
|
by: block111 |
last post by:
Hello,
code like this:
int f1(int x){
int f2(int y){
return y*y;
}
if(x > 0)
return f2(x);
|
by: Gregory Petrosyan |
last post by:
I often make helper functions nested, like this:
def f():
def helper():
...
...
is it a good practice or not? What about performance of such
constructs?
|
by: Josiah Manson |
last post by:
I found that I was repeating the same couple of lines over and over in
a function and decided to split those lines into a nested function
after copying one too many minor changes all over. The only problem is
that my little helper function doesn't work! It claims that a variable
doesn't exist. If I move the variable declaration, it finds the
variable, but can't change it. Declaring the variable global in the
nested function doesn't work...
| |
by: Wolfgang Draxinger |
last post by:
If you know languages like Python or D you know, that nested
functions can be really handy.
Though some compilers (looking at GCC) provide the extension of
nested functions, I wonder, how one could implement an
equivalent behaviour with plain C (in this case I'm thinking of
the language I'm developing, which shall be converted into C for
target compilation). So far I didn't touch the topic "nested
functions", since I just don't see an...
|
by: Maric Michaud |
last post by:
Le Tuesday 12 August 2008 23:15:23 Calvin Spealman, vous avez écrit :
I was not aware of any "nested classes are unsupported" before and didn't
consider nested classes as bad practice till now, even with the pickle
limitation (not every class are intended to be pickled), more you didn't give
any evidence or any pertinent quote of this and at least one of Guido in the
above threads seems contradict you :...
|
by: Gabriel Rossetti |
last post by:
Hello,
I can't get getattr() to return nested functions, I tried this :
.... def titi():
.... pass
.... f = getattr(toto, "titi")
.... print str(f)
....
Traceback (most recent call last):
|
by: brasse |
last post by:
Hello!
I have been running in to some problems when using
contextlib.nested(). My problem arises when using code similar to
this:
from __future__ import with_statement
from contextlib import nested
|
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...
|
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
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...
|
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...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
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...
| |