Default scope of variables

Steven D'Aprano steve+comp.lang.python at
Thu Jul 4 18:38:28 CEST 2013

On Thu, 04 Jul 2013 15:47:57 +1000, Chris Angelico wrote:

> On Thu, Jul 4, 2013 at 3:32 PM, Steven D'Aprano
> <steve+comp.lang.python at> wrote:
>> Accidental shadowing can be a problem, but I've never heard of anyone
>> saying that they were *forced* to shadow a global they needed access
>> to. Just pick a different name.
> Here's one example of shadowing that comes from a C++ project at work. I
> have a class that represents a database transaction (constructing it
> begins a transaction, it has methods for doing queries, and its
> destructor rolls back). 

When the object finally gets garbage collected, doesn't that mean the 
last transaction will be rolled back?

> There's also a class for a subtransation (same
> thing, but it uses savepoints within the transaction). So to bracket a
> piece of code in a subtransaction, I want to declare a new
> subtransaction object with the same name as the outer transaction
> object, and then dispose of it and "reveal" the original. There will
> always be an object called "trans", and it will always be the
> appropriate transaction to do queries on, but it'll change what it is.

You don't need to introduce such scoping rules for variables for that use-
case. We have namespaces (classes) for that sort of thing :-) 

Python 3.3's ChainMap is probably a better solution, but here's another 
way to get the same sort of behaviour:

def function():
    class Namespace:
        # Set a class attribute.
        trans = Transaction()
    ns = Namespace()
    # Enter a subtransaction.
    ns.trans = Subtransaction()
    del ns.trans

Yes, it looks weird to see ns.trans used immediately after deleting it, 
but that's because it is a weird (or at least unusual) use-case.


More information about the Python-list mailing list