Where do nested functions live?
Ben Finney
bignose+hates-spam at benfinney.id.au
Sat Oct 28 04:05:44 EDT 2006
"Steven D'Aprano" <steve at REMOVE.THIS.cybersource.com.au> writes:
> 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
More information about the Python-list
mailing list