namespaces

Kay Schluehr kay.schluehr at gmx.net
Sun Jul 31 16:38:13 EDT 2005


Paolino wrote:

> The second point also shows my perplexities about functions namespace:
>
> def function():
>    function.foo='something'
>
> a=function.foo
>
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
> AttributeError: 'function' object has no attribute 'foo'
>
> How should I read it? The namespace is half done inside the function?

Don't know what you mean with "half done"?

In order to understand Python you have to care about it's dynamic
nature. The "def function()" is an executable definition that produces
a function object that gets bound to a new global name "function".
After "function" is created it may be manipulated inside it's own body
much like it is possible to call it recursively. That's why this should
work:

def function():
    function.foo='something'

>>> function()
>>> a=function.foo

By the way. Did you understand the hint Paul Rubin tried to offer?
Defining an __all__ = [...] variable in your module makes exactly those
names visible to other modules that are contained in the list. You
might pollute your modules namespace but this is exactly what is it
good for. You just have to care not to pollute the namespaces of other
modules preserving locality.

Kay




More information about the Python-list mailing list