Another Language Change for Debate
Ben Wolfson
wolfson at uchicago.edu
Sun Jan 13 02:43:39 EST 2002
On Fri, 11 Jan 2002 21:10:21 -0600, Gareth McCaughan wrote:
> I much prefer a different approach.
>
> class MyClass:
> def staticmethod bar(y):
> blah()
> stuff += stuff
> def classmethod baz(z):
> return 1
>
> This generalizes in an obvious way:
> def <name1> <name2>(<formals>): <body>
> turns into
> def <name2>(<formals>): <body>
> <name2> = <name1>(<name2>)
> which would make it possible, e.g., to define
> a function called "memo" which memoizes its argument
> and say (typical useless example follows):
> def memo fib(n):
> if n<2: return n
> return fib(n-2)+fib(n-1)
> and get only O(n) calls to "fib" on doing fib(n).
You can achieve something similar with a metaclass:
class funcmodifier(type):
def __init__(cls, name, bases, dict):
super(funcmodifier, cls).__init__(name, bases, dict)
replace = {}
for name,value in dict.iteritems():
if callable(value) and cls._isvalidname(name):
modname, funcname = name.split('_',1)
try:
f = sys._getframe(1) #caller's frame
mod = eval(modname, f.f_globals, f.f_locals)
except NameError: continue
if not callable(mod): continue
func = mod(value)
replace[name] = (funcname, func)
for name, (newname, func) in replace.iteritems():
delattr(cls, name)
setattr(cls, newname, func)
def _isvalidname(name):
if name.startswith('_'): return 0
has_uscore = name.count('_')
if has_uscore == 1 and name.endswith('_'): return 0
return has_uscore
_isvalidname = staticmethod(_isvalidname)
>>> class Hungarian:
__metaclass__ = funcmodifier
def classmethod_hovercraft(*a): print a
def staticmethod_eels(*a): print a
>>> h = Hungarian()
>>> h.hovercraft('blah')
(<class '__main__.Hungarian'>, 'blah')
>>> h.eels('la','dee','da')
('la', 'dee', 'da')
>>>
--
BTR
BEN WOLFSON HAS RUINED ROCK MUSIC FOR A GENERATION
-- Crgre Jvyyneq
More information about the Python-list
mailing list