Overriding a global

Jean-Michel Pichavant jeanmichel at sequans.com
Wed Dec 14 05:14:53 EST 2011


Joshua Landau wrote:
> On 13 December 2011 13:30, Jean-Michel Pichavant 
> <jeanmichel at sequans.com <mailto:jeanmichel at sequans.com>> wrote:
>
>     writing
>
>     x = 1
>
>     def spam():
>       x = 2
>
>     is in general a bad idea. That was my point.
>
>
> Why? I have a few (probably wrong) guesses.
>
> Because you expect it to be the same every time you use it?
> Well, then this should be "in general a bad idea":
> x = 1; print(x); x = 2; print(x)
you're changing the value of x, that's fine. In the example above, the 
assignement is not the problem. The problem is that you create 2 
different 'x', one in globals(), and one in locals(). Using the same 
name within 2 implicit namespaces is a bad idead in general because it 
can be difficult to know which one is used.

If you want to have fun, try this code, prepared to be amazed. There's 
something funny with the global statement, it's applied on the whole 
block no matter where it is stated in the block.
x=1 # global

def spam():
    x = 2 # local (or so you may think)
    print x
    global x # I need to use the global one now
    print x
    print locals()

For more fun you could create a 'x' name in __builtin__ and import it so 
that people never know which x you are using.

> Even though it makes total sense to me.
>
> Is it because it's used to different purpose between similarly-looking 
> functions?
> This looks fine, though:
> def func1(): x=1; print(x)
> def func2(): x=2; print(x)
>
> Is it because it looks like a reassignment of the more global x?
> I don't have an example here but, simply put, I don't believe this. We 
> can use "id" as our own local variable without thinking that we're 
> tampering with "__builtins__.id". I don't see it as much of a leap 
> from builtin to global (except that you /*can*/ do "dir = 1; del dir; 
> dir" without error).
>
> That said, I'm sorta' just guessing the reason you might think it's a 
> bad idea.

The problem makes little sense when using names like x or func1. Besides 
namespace issues, naming 2 *different objects* with the same meaningful 
name is usually a bad idea and points the fact that your names are no 
that meaningful. To go back to the original post, having a 'logger' that 
may name 2 different logger object during the execution is a bad idea. 
One quick way to fix it is to name the logger 'currentLogger', this way 
you warn the reader that the logger named by curentLogger may change 
over time.

As someone sugggested in this thread one other option is to use a 
different name for the second logger.

JM



More information about the Python-list mailing list