Mangle function name with decorator?
Michele Simionato
michele.simionato at gmail.com
Wed Mar 18 00:58:00 EDT 2009
On Mar 17, 7:45 pm, Aaron Brady <castiro... at gmail.com> wrote:
> (Perhaps someday, we will be able to write:
> def dec( namespace ):
> def outer( fun ):
> if fun.__name__ in namespace:
> namespace[ dup_var ]= namespace[ fun.__name__ ]
> return fun
> return outer
> It allows us to see if there's a prior entry in the current namespace,
> and save it to a different name.)
Not in the future, but right now, with Python 3.0:
class noclashdict(dict):
"""
A dictionary where overriding a name actually generates a new
entry
with suffix '_new':
>>> d = noclashdict()
>>> d['a'] = 1
>>> d['a'] = 2
>>> sorted(d)
['a', 'a_new']
"""
def __setitem__(self, name, value):
setitem = super().__setitem__
if name in self:
setitem(name + "_new", value)
else:
setitem(name, value)
class Meta(type):
"A metaclass replacing the class dictionary with a noclashdict in
its instances"
@classmethod
def __prepare__(cls, name, bases):
return noclashdict()
class C(metaclass=Meta):
def foo(self):
return 1
def foo(self):
return 2
print(sorted(n for n in vars(C) if not n.startswith('__')))
# prints ['foo', 'foo_new']
if __name__ == '__main__':
import doctest; doctest.testmod()
It seems Guido's time machine is ticking again ;)
Michele Simionato
More information about the Python-list
mailing list