473,574 Members | 3,118 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

decorators and multimethods

Decorators can generate endless debate about syntax, but can also
be put to better use ;)

Actually I was waiting for decorators to play a few tricks that were
syntactically too ugly to be even imaginable for Python 2.3.

One trick is to use decorators to implement multimethods. A while ago
Howard Stearns posted here a recipe to implement generic functions
a.k.a multimethods.

I have not studied his recipe, so don't ask me how it works. All I
did was to add an "addmethod" function and save his code in a module
called genericfunction s.

Decorators allowed me to use the following syntax:

# BEGIN generic functions in Python, example
# use code and examples from Howard Stearns

from genericfunction s import Generic_Functio n, addmethod

foo = Generic_Functio n()

@addmethod(obje ct, object, object)
def foo(_, x, y, z):
return 'default'

@addmethod(int, int, int)
def foo(call_next, x, y, z):
return 'all ints , ' + call_next(x, y, z)

@addmethod(obje ct, object)
def foo( _, x, y):
return 'just two'

print foo # the multimethod table as a dictionary
print foo(1, 2, 'three') # => default
print foo(1, 2, 3) # => all ints, default
print foo(1, 'two') #> just two
print foo('oops') #=> genericfunction s.NoNextMethod error

# END generic functions in Python, example

Howard Stearns' code is posted here
http://groups.google.it/groups?hl=it...net%26rnum%3D1

I just added the following function:

import sys

def addmethod(*type s):
"""sys._getfram e hack; works when the generic function is defined
in the globals namespace."""
caller_globs = sys._getframe(1 ).f_globals
def function2generi c(f):
generic = caller_globs[f.func_name]
generic[types] = f
return generic
return function2generi c

Decorators did all the rest ;) Just to add an use case I haven't
seen before.

Michele Simionato
Jul 18 '05 #1
8 1603
Hey, that's pretty nice. I'll have to get some coffee and study this. What
do I read about? I can't find anything about @ or 'decorator' in the 2.3
documentation. What should I be looking for?

Michele Simionato wrote:
Decorators can generate endless debate about syntax, but can also
be put to better use ;)

Actually I was waiting for decorators to play a few tricks that were
syntactically too ugly to be even imaginable for Python 2.3.

One trick is to use decorators to implement multimethods. A while ago
Howard Stearns posted here a recipe to implement generic functions
a.k.a multimethods.

I have not studied his recipe, so don't ask me how it works. All I
did was to add an "addmethod" function and save his code in a module
called genericfunction s.

Decorators allowed me to use the following syntax:

# BEGIN generic functions in Python, example
# use code and examples from Howard Stearns

from genericfunction s import Generic_Functio n, addmethod

foo = Generic_Functio n()

@addmethod(obje ct, object, object)
def foo(_, x, y, z):
return 'default'

@addmethod(int, int, int)
def foo(call_next, x, y, z):
return 'all ints , ' + call_next(x, y, z)

@addmethod(obje ct, object)
def foo( _, x, y):
return 'just two'

print foo # the multimethod table as a dictionary
print foo(1, 2, 'three') # => default
print foo(1, 2, 3) # => all ints, default
print foo(1, 'two') #> just two
print foo('oops') #=> genericfunction s.NoNextMethod error

# END generic functions in Python, example

Howard Stearns' code is posted here
http://groups.google.it/groups?hl=it...net%26rnum%3D1

I just added the following function:

import sys

def addmethod(*type s):
"""sys._getfram e hack; works when the generic function is defined
in the globals namespace."""
caller_globs = sys._getframe(1 ).f_globals
def function2generi c(f):
generic = caller_globs[f.func_name]
generic[types] = f
return generic
return function2generi c

Decorators did all the rest ;) Just to add an use case I haven't
seen before.

Michele Simionato


Jul 18 '05 #2
Michele Simionato wrote:
def addmethod(*type s):
"""sys._getfram e hack; works when the generic function is defined
in the globals namespace."""
caller_globs = sys._getframe(1 ).f_globals
def function2generi c(f):
generic = caller_globs[f.func_name]
generic[types] = f
return generic
return function2generi c


Couldn't you use f.func_globals to avoid the getframe hack?

Regards,
Martin
Jul 18 '05 #3
Michele Simionato wrote:
foo = Generic_Functio n()

@addmethod(obje ct, object, object)
def foo(_, x, y, z):
return 'default'


On a second note, I would probably prefer a different notation

foo = Generic_Functio n()

@foo.overload(o bject, object, object)
def foo(_, x, y, z):
return 'default'

This, of course, requires changes to Generic_Functio n, but
they could be as simple as

def overload(self, *types):
def decorator(f):
self[types] = f
return self
return decorator

Regards,
Martin
Jul 18 '05 #4
mi************* **@gmail.com (Michele Simionato) wrote in message news:<4e******* *************** ****@posting.go ogle.com>...

<snip using decorators as syntactic sugar over Howard Stearns module>

Martin v. Lewis suggested an improvement, which involves adding the
following method to the Generic_Functio n class:

def addmethod(self, *types):
"My own tiny modification to Stearns code"
return lambda f: self.setdefault (types,f)

The advantage is that methods definitions can go in any scope now and
not only at the top level as in my original hack.
My previous example read:

foo = Generic_Functio n()

@foo.addmethod( object, object, object)
def _(call_next, x, y, z):
return 'default'

@foo.addmethod( int, int, int)
def _(call_next, x, y, z):
return 'all ints , ' + call_next(x, y, z)

@foo.addmethod( object, object)
def _(call_next, x, y):
return 'just two'

where I use "_" as a poor man anonymous function. I cannot reuse the name
"foo" now, since

@foo.addmethod( ...)
def foo(..):
....

is really converted to

def foo(..)
...

foo=foo.addmeth od(...)(foo)

and this would correctly raise a "foo function has not attribute addmethod"!
But in some sense this is better, since we avoid any confusion
between the member functions and the generic function (which is implemented
as a dictionary, BTW).

Michele Simionato
Jul 18 '05 #5

On 7-aug-04, at 17:42, Michele Simionato wrote:

where I use "_" as a poor man anonymous function. I cannot reuse the
name
"foo" now, since

@foo.addmethod( ...)
def foo(..):
....

is really converted to

def foo(..)
...

foo=foo.addmeth od(...)(foo)


No it isn't. The decorators are called before the function is added to
a namespace, e.g. it's more like:

def _():
def foo(..):
..
return foo

foo = foo.addmethod(. ..)(_())

Ronald

Jul 18 '05 #6
Ronald Oussoren <ro************ @mac.com> wrote in message news:<ma******* *************** *************** *@python.org>.. .
decorators are called before the function is added to
a namespace


You are right. I did some experiment with

def dec(f):
print globals()
return f

and it is clear that

@dec
def f():
pass

is NOT the same as

def f():
pass
f=dec(f)

Using the @decorator, f is not in the globals at the decorator call time.
In the version of the PEP I have read (that my have changed) complete
equivalence was claimed, so I assumed (wrongly) this was the cause of
the error I saw. Instead the error came from the second call to the
decorator, not from the first one.

Michele
Jul 18 '05 #7
mi************* **@gmail.com (Michele Simionato) wrote in message news:<4e******* *************** ****@posting.go ogle.com>...

One trick is to use decorators to implement multimethods. A while ago
Howard Stearns posted here a recipe to implement generic functions
a.k.a multimethods.

I have not studied his recipe, so don't ask me how it works. All I
did was to add an "addmethod" function and save his code in a module
called genericfunction s.

Decorators allowed me to use the following syntax:

# BEGIN generic functions in Python, example
# use code and examples from Howard Stearns

from genericfunction s import Generic_Functio n, addmethod

foo = Generic_Functio n()

@addmethod(obje ct, object, object)
def foo(_, x, y, z):
return 'default'

@addmethod(int, int, int)
def foo(call_next, x, y, z):
return 'all ints , ' + call_next(x, y, z)

@addmethod(obje ct, object)
def foo( _, x, y):
return 'just two'


FYI, there's another example of this approach available in PyProtocols
CVS; see:

http://www.eby-sarna.com/pipermail/p...ly/001598.html

It uses this syntax:

from protocols.dispa tch import when, next_method
[when("True")]
def foo(x,y,z):
return "default"

[when("x in int and y in int and z in int")]
def foo(x,y,z):
return "all ints, "+next_method(x ,y,z)

but will work with Python 2.2.2 and up. It also allows arbitrary
expressions to be used to distinguish multimethod cases, not just type
information, but still optimizes them to table lookups. It doesn't
support variadic or default arguments yet, though.
Jul 18 '05 #8
Michele Simionato wrote:
mi************* **@gmail.com (Michele Simionato) wrote in message news:<4e******* *************** ****@posting.go ogle.com>...

<snip using decorators as syntactic sugar over Howard Stearns module>

Martin v. Lewis suggested an improvement, which involves adding the
following method to the Generic_Functio n class:

def addmethod(self, *types):
"My own tiny modification to Stearns code"
return lambda f: self.setdefault (types,f)

The advantage is that methods definitions can go in any scope now and
not only at the top level as in my original hack.
My previous example read:

foo = Generic_Functio n()

@foo.addmethod( object, object, object)
def _(call_next, x, y, z):
return 'default'

@foo.addmethod( int, int, int)
def _(call_next, x, y, z):
return 'all ints , ' + call_next(x, y, z)

@foo.addmethod( object, object)
def _(call_next, x, y):
return 'just two'

where I use "_" as a poor man anonymous function. I cannot reuse the name
"foo" now, since

@foo.addmethod( ...)
def foo(..):
....

is really converted to

def foo(..)
...

foo=foo.addmeth od(...)(foo)

and this would correctly raise a "foo function has not attribute addmethod"!
But in some sense this is better, since we avoid any confusion
between the member functions and the generic function (which is implemented
as a dictionary, BTW).


Another benefit is you can give the different variants real names:

@foo.addmethod( object, object):
def add_objects(cal l_next, x, y):
return 'just two'

so you can call it directly if you want

David
Jul 18 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2052
by: Michael Sparks | last post by:
Anyway... At Europython Guido discussed with everyone the outstanding issue with decorators and there was a clear majority in favour of having them, which was good. From where I was sitting it looked like about 20:20 split on the following syntaxes: 1 def func(arg1, arg2, arg3) : function... 2 def func(arg1, arg2, arg3):...
4
1478
by: RebelGeekz | last post by:
Just my humble opinion: def bar(low,high): meta: accepts(int,int) returns(float) #more code Use a metadata section, no need to introduce new messy symbols, or mangling our beloved visual cleanliness of python.
1
1807
by: Stephen Thorne | last post by:
Decorators have been getting lots of air-time at the moment, but only really the syntax. After a short discussion on irc the other night I decided to download python2.4 from experimental and write out some truely worthy decorator hacks. I implemented multimethods as a warm-up, and then implemented tail call elimination. Presented here is a...
2
1699
by: Guido van Rossum | last post by:
Robert and Python-dev, I've read the J2 proposal up and down several times, pondered all the issues, and slept on it for a night, and I still don't like it enough to accept it. The only reason to accept it would be to pacify the supporters of the proposal, and that just isn't a good enough reason in language design. However, it got...
0
2335
by: Anthony Baxter | last post by:
To go along with the 2.4a3 release, here's an updated version of the decorator PEP. It describes the state of decorators as they are in 2.4a3. PEP: 318 Title: Decorators for Functions and Methods Version: $Revision: 1.34 $ Last-Modified: $Date: 2004/09/03 09:32:50 $ Author: Kevin D. Smith, Jim Jewett, Skip Montanaro, Anthony Baxter
14
1805
by: Gabriel Zachmann | last post by:
This post is not strictly Python-specific, still I would like to learn other university teachers' opinion. Currently, I'm teaching "introduction to OO programming" at the undergrad level. My syllabus this semester consists of a bit of Python (as an example of a scripting language) and C++ (as an example of a compiled language). With C++, I...
0
1096
by: Roman Suzi | last post by:
hi! I've found one more nice use case for decorators. I feel multimethods could be made even nicier by defining multimethods inside special class. But I have not figured out how to do it yet. #!/bin/env python2.4 if "We have Neel Krishnaswami module Multimethod.py": import Multimethod
2
1945
by: Andrew West | last post by:
Probably a bit of weird question. I realise decorators shouldn't be executed until the function they are defined with are called, but is there anyway for me to find all the decorates declared in a file when I import it? Or perhaps anyway to find the decorators by loading the file by other methods (with out simply parsing it by hand). ...
18
2485
by: Richard Szopa | last post by:
Hello all, I am playing around w/ Python's object system and decorators and I decided to write (as an exercise) a decorator that (if applied to a method) would call the superclass' method of the same name before doing anything (initially I wanted to do something like CLOS :before and :end methods, but that turned out to be too difficult)....
0
7841
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7760
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8271
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8137
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6511
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5654
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3793
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1369
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1099
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.