invoking multiple methods (Was: Python vs. Ruby)
Andrew Dalke
adalke at mindspring.com
Fri Jan 10 12:36:58 EST 2003
Jack Diederich:
> Some people seem to like lists, etc to return an lvalue and other
> people think it dilutes the language. To borrow from another language
> would something like
>
> import lvalues from pragma
>
> be acceptable?
> The return values that are currently None would then be self for all
> calls in that module.
I futzed around with an idea for how to do this without an explicit
pragma. It implements your idea that "if it returns None, return the
original object instead" and without the qualifications I added about
the difference between explicit and implicit None return values.
As in another thread, "FOR ENTERTAINMENT PURPOSES ONLY"
class PragmaMethod:
def __init__(self, obj, method):
self.__dict__["_PragmaMethod__obj"] = obj
self.__dict__["_PragmaMethod__method"] = method
def __getatrr__(self, name):
return getattr(self.__method, name)
def __call__(self, *args, **kwargs):
x = self.__method(*args, **kwargs)
if x is None:
return Pragma(self.__obj)
return x
class Pragma:
def __init__(self, obj):
self.__dict__["_Pragma__obj"] = obj
def __getattr__(self, name):
x = getattr(self.__obj, name)
if callable(x):
return PragmaMethod(self.__obj, x)
return x
def test():
a = [1, 5, 3]
a = Pragma(a)
a.sort().reverse()
assert a == [5, 3, 1]
assert a[0] == 5
assert a.reverse()[0] == 1
if __name__ == "__main__":
test()
This could be expanded in many ways. For example, you
could make it so you list which attributes should be
handled this way as compared to normal behaviour. Perhaps
as
Pragma(a, ["sort", "reverse"])
Andrew Dalke
dalke at dalkescientific.com
More information about the Python-list
mailing list