Another Language Change for Debate
Gareth McCaughan
Gareth.McCaughan at pobox.com
Sat Jan 12 10:06:48 EST 2002
Tim Peters wrote:
[I suggested the following:]
> >
> > 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>)
[etc]
>
> It's more that a gazillion "toy parser" tools out there (from Emacs
> python-mode to Python's own pyclbr.py) would have to be changed too, lest
> they all end up thinking you have an unbounded number of methods named
> "staticmethod" (etc). You won't take this seriously until a dozen legacy
> tools you don't even remember you're using break <wink>.
Ah yes. That would be a shame. So here's a variant.
class MyClass:
def bar(y) [staticmethod]:
do_some_stuff()
return 123
By the way, if you define generator(x) to be the same
as iter(x) then that lets you say
def f(x) [generator]:
while 1:
yield x
x=x+1
after which f *is* a generator, not a function that returns
a generator. I don't think this is worth doing :-).
The manic generalizer in me wants to add that if you have
several modifiers you want to apply to a function or method,
you can say
def f(x) [memoized,classmethod,ignoring_errors]:
<stuff>
but I'm not sure whether that's elegant or gratuitous
just yet. By the way, for anyone who's curious, here are
rough approximations to the first and last of those
modifiers:
def memoized(f):
d = {}
def _(*args):
try: return d[args]
except KeyError:
result = f(*args)
d[args] = result
return result
return _
def ignoring_errors(f):
def _(*args):
try: return f(*args)
except: return None
return _
Note that "ignoring_errors" may be a misleading name,
since an error will still terminate execution of the
underlying function.
--
Gareth McCaughan Gareth.McCaughan at pobox.com
.sig under construc
More information about the Python-list
mailing list