[Python-Dev] Scoping [Patience, please]

Paul Moore p.f.moore at gmail.com
Wed Jan 31 16:44:06 CET 2007


On 31/01/07, lingwitt at gmail.com <lingwitt at gmail.com> wrote:
> Fortunately, the scopes in question are always named.
> Can't we just reference what's already there?
>
>  >>> x = 10
>  >>> def a():
> ...     x = 3
> ...     def b():
> ...         a.x = 4
> ...         print a.x
> ...
> ...     b()
> ...     print x
> ...
>  >>> a()
> 4
> 4
>  >>> print x
> 10

There is further research you need to do, as this option has been
discussed before. I'm not sure if it's in the PEP, but it has
certainly come up on the mailing list - you should check the archives
for more information.

Basically, you can't use "a.x" as the function a has not yet been
created - you are still executing the "def". So you don't have access
to the function object's attributes in the way you need. (The
technical details are beyond me, and that explanation probably shows
it, but I hope you get the gist :-))

> Of course, the module itself is unnamed, and it would
> be completely consistent to use the single prefixed dot
> to reference it:
>
>  >>> x = 10
>  >>> def a():
> ...     x = 3
> ...     def b():
> ...         a.x = 4
> ...         print a.x
> ...
> ...    .x = 5
> ...     b()
> ...     print x
> ...
>  >>> a()
> 4
> 4
>  >>> print x
> 5

Yuk.

> However, I would think a placeholder is easier to spot:
>
>  >>> x = 10
>  >>> def a():
> ...     x = 3
> ...     def b():
> ...         a.x = 4
> ...         print a.x
> ...
> ...    @.x = 5
> ...     b()
> ...     print x
> ...
>  >>> a()
> 4
> 4
>  >>> print x
> 5

Double yuk.

> Be gentle.

Sorry, I could probably have been more gentle :-) Seriously, thanks
for your interest, and don't be put off, but if you pick up on a
long-standing proposal like this, you really do need to do a lot of
research. Many of the obvious, a lot of the not-so-obvious, and even
some of the downright stupid options will have already been discussed,
and you can't always guarantee that everything gets captured in the
PEP. Checking the list archives is always a good idea.

If you want to get involved without needing to do quite so much
pre-work, joining in on one of the current threads is often a good way
to start.

Hope this helps,
Paul.


More information about the Python-Dev mailing list