(newbie) Is there a way to prevent "name redundancy" in OOP ?

Carl Banks pavlovevidence at gmail.com
Sat Jan 6 02:57:00 CET 2007


Martin Miller wrote:
> ### non-redundant example ###
> import sys
>
> class Pin:
>     def __init__(self, name, namespace=None):
>         self.name = name
>         if namespace == None:
>             # default to caller's globals
>             namespace = sys._getframe(1).f_globals
>         namespace[name] = self
>
> Pin('aap')       # create a Pin object named 'aap'
> Pin('aap2')     # create a Pin object named 'aap2'
> print aap.name
> print aap2.name

The problem with this is that it only works for global namespaces,
while failing silently and subtly if used in a local namespace:

def fun():
    Pin('aap')
    aap1 = aap
    fun2()
    aap2 = aap
    print aap1 is aap2

def fun2():
    Pin('aap')

If it's your deliberate intention to do it with the global namespace,
you might as well just use globals() and do it explicitly, rather than
mucking around with Python frame internals.  (And it doesn't make the
class unusable for more straightforward uses.)

for _name in ('aap','dcr'):
    globals()[_name] = Pin(_name)
del _name


Carl Banks




More information about the Python-list mailing list