473,836 Members | 1,608 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Where do nested functions live?

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.

Oct 28 '06 #1
23 1978
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>

Oct 28 '06 #2
"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

Oct 28 '06 #3
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

Oct 28 '06 #4
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>

Oct 28 '06 #5
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.

Oct 28 '06 #6
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
Oct 28 '06 #7
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
Oct 28 '06 #8
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
Oct 28 '06 #9
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
Oct 28 '06 #10

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

Similar topics

6
2572
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
6
12207
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 {
7
2257
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);
9
2860
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?
78
4991
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...
4
2317
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...
0
143
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 :...
9
3994
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):
7
1990
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
0
9825
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, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9671
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10596
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10255
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
9382
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 projectplanning, coding, testing, and deploymentwithout 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
6980
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
5651
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
5829
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3116
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.