[MERGE] Repository.iter_files_bytes()

Andrew Bennetts andrew.bennetts at canonical.com
Thu Mar 26 22:21:51 GMT 2009


John Arbash Meinel wrote:
[...]
> I'm pretty sure that the issue is that gettext sets the "_"
> function/operator/variable in "__builtins__". The wanted to do that so
> it would be available everywhere, without having to do "from gettext
> import gettext as _" at the top of every module (bringing it into your
> globals).
> 
> However, as a builtin, it then has a single binding, and assigning to it
> *modifies the builtin*.

Huh?  That's not what builtins mean.

> So try:
> 
> # foo.py
> import __builtins__
> __builtins__.x = 1
> 
> def func():
>   x = 2
> func()
> print x

That prints 1 (once you fix it to s/__builtins__/__builtin__, or paste it in the
interactive interpreter rather than a separate file, same result either way).

Assignment inside a function *always* only changes a local, unless:

  * the LHS is not just plain identifier, e.g. “foo.bar” obviously doesn't
    assign to a local; or
  * there is “global” declaration for that variable in the function.

(Python 3 adds a “nonlocal” declaration, but that's the same sort of thing as
“global”.)

You may be thinking of the case when a variable is used but not assigned in a
function, *then* Python will search through the outer scopes (cells if there is
a nested function, then module globals, then builtins) to try find it.  But
assignment to an identifier in a function always makes that identifier a local
(even in lines before the assignment in that function, which tends to cause
UnboundLocalErrors), unless you've explicitly told Python otherwise with global.

So my confusion about what's wrong with using “_” still stands.

-Andrew.




More information about the bazaar mailing list