473,695 Members | 3,385 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

AntiDecorator metaclass

One of the beautiful things about Python is its clear, minimal syntax.
So we must resist adding new syntax to the language, especially where
there is a reasonable alternative.

I believe that Stefen Eischet's suggestion for automatically determining
a method's type (class/instance/static) from the name of its first
formal parameter is a reasonable alternative to any/all of the decorator
syntax proposals.

Just as the Python system relies on indentation conventions to denote
the programmer's intended block structure, it could just as well rely on
parameter naming conventions to denote method types. And as long as
these conventions feel natural to the programmer, the language retains
its beauty.

So here is a metaclass that illustrates (what I believe is) the
essential idea behind Stefen's suggestion. See the docstring and
footnotes for a description of what it does.

############### ############### ############### ############### ######
class AntiDecorator(t ype):
""" Metaclass that protests against decorator syntax :-)

This metaclass infers a method's method type (instance, class,
or static) from the name of its first formal parameter, then
makes the necessary Python declaration.

* If the 1st parm's name is 'self', then the method is
an instance method.

* If the 1st parm's name is 'cls' or 'klass', then the
method is a class method.

* All other methods are static methods.

-------------------------------------------------
The essence of this technique was suggested by
Stefan Eischet on the comp.lang.pytho n newsgroup.
-------------------------------------------------

This is freeware, no warranties, etc...

"""
__author__ = 'Paul Morrow <pm****@yahoo.c om>'
__credits__ = 'Stefen Eischet <st****@eischet .com>'
__date__ = '13 Aug 04'
__version__ = '0.1'

def __new__(cls, clsName, bases, dict):
import inspect, types
for fName in dict.keys():
f = dict[fName] # 1.
if type(f) is types.FunctionT ype: # 2.
parmNames = inspect.getargs pec(f)[0] # 3.
if parmNames: # 4.
if parmNames[0] in ('cls', 'klass'): # 5.
dict[fName] = classmethod(f)
elif parmNames[0] == 'self': # 6.
pass
else: # 7.
dict[fName] = staticmethod(f)
else: # 8.
dict[fName] = staticmethod(f)
return type.__new__(cl s, clsName, bases, dict)
"""Footnote s:
1. Bind f to an attribute of the class (cls).
2. Only work this magic on functions.
3. Get the function's formal parameter names.
4. If it has formal parameters, we'll use them
to determine what kind of function it is.
5. It's a class method if its first formal
parameter is 'cls' or 'klass'.
6. It's an instance method (default) if its first
formal parm is 'self'
7. It's a static method if it's not a class method
or instance method.
8. No formal parameters, so it's a static method.
"""

class Object(object):
""" Uses AntiDecorator metaclass to infer method type. """
__metaclass__ = AntiDecorator

if __name__ == '__main__':
class Foo(Object):
def imethod(self, parm):
print "I'm an instance method: %s." % parm
def cmethod(cls, parm):
n = cls.__name__
print "I'm a class method (of %s): %s." % (n, parm)
def smethod(parm):
print "I'm a static method: %s." % parm

Foo().imethod(' alpha')
Foo.smethod('be ta')
Foo.cmethod('ga mma')
############### ############### ############### ############### ######

Jul 18 '05 #1
4 1571
Paul Morrow wrote:
One of the beautiful things about Python is its clear, minimal syntax.
So we must resist adding new syntax to the language, especially where
there is a reasonable alternative.

I believe that Stefen Eischet's suggestion for automatically determining
a method's type (class/instance/static) from the name of its first
formal parameter is a reasonable alternative to any/all of the decorator
syntax proposals.


Here is another one that forgot that decorators aren't limited to
classmethod and staticmethod. Therefore, that proposal alone isn't an
alternative to any other syntax.

If you want to say that decorators should be limited to classmethod and
staticmethod, say it and give us a good reason, a very very good reason.
Jul 18 '05 #2
Christophe Cavalaria wrote:
Paul Morrow wrote:

One of the beautiful things about Python is its clear, minimal syntax.
So we must resist adding new syntax to the language, especially where
there is a reasonable alternative.

I believe that Stefen Eischet's suggestion for automatically determining
a method's type (class/instance/static) from the name of its first
formal parameter is a reasonable alternative to any/all of the decorator
syntax proposals.

Here is another one that forgot that decorators aren't limited to
classmethod and staticmethod. Therefore, that proposal alone isn't an
alternative to any other syntax.

If you want to say that decorators should be limited to classmethod and
staticmethod, say it and give us a good reason, a very very good reason.


No I don't want to say that. I want to say that decorators should keep
their nose out of the classmethod/staticmethod business. There's a
perfectly good *no-extra-syntax-required* way to do that, thru the
leveraging of conventions that most developers use already (give or take
the spelling of the class parameter). The code remains readable,
intuitive, obvious, unintimidating. And it makes the problem space that
decorators address smaller (as it becomes everything you want decorators
to do minus the classmethod/staticmethod stuff), which might give rise
to a better, less objectionable solution.

Jul 18 '05 #3
On Sat, 14 Aug 2004 08:15:43 -0400, Paul Morrow <pm****@yahoo.c om> wrote:
No I don't want to say that. I want to say that decorators should keep
their nose out of the classmethod/staticmethod business.
So what's the point of this, then? You say it's an "anti-decorator" metaclass.
It's not. It's simply a way to automagically invoke a couple of standard
decorators from a metaclass, based on people following a convention.

It does little or nothing to address many of the other requirements for
decorators, is brittle (see my previous post on the subject) and relies on
something that is merely a convention, and deliberately so.
And it makes the problem space that
decorators address smaller (as it becomes everything you want decorators
to do minus the classmethod/staticmethod stuff), which might give rise
to a better, less objectionable solution.


I fail to see how your hack, which merely removes two of the most trivial
examples of decorator use, addresses anything in the general case.

As far as a "better, less objectionable solution" - as I've said time and time
again, this subject has had 2+ years of discussion. Do you honestly
expect that 2 or 3 more weeks here or there is going to produce some
blinding flash of insight? I'd love it to be true, but really, I can't see it.
Jul 18 '05 #4
Anthony Baxter wrote:
On Sat, 14 Aug 2004 08:15:43 -0400, Paul Morrow <pm****@yahoo.c om> wrote:
No I don't want to say that. I want to say that decorators should keep
their nose out of the classmethod/staticmethod business.

So what's the point of this, then? You say it's an "anti-decorator" metaclass.
It's not. It's simply a way to automagically invoke a couple of standard
decorators from a metaclass, based on people following a convention.

It does little or nothing to address many of the other requirements for
decorators, is brittle (see my previous post on the subject) and relies on
something that is merely a convention, and deliberately so.


The class was named a little prematurely, but the point was to show that
decorator syntax wasn't needed for static or class method declarations
as simply following a convention does the job just fine. Just as it
does for private and semi-private methods. Are we planning on keeping
that convention? Or will we be phasing that out in favor of a method
visibility decorator?
And it makes the problem space that
decorators address smaller (as it becomes everything you want decorators
to do minus the classmethod/staticmethod stuff), which might give rise
to a better, less objectionable solution.

I fail to see how your hack, which merely removes two of the most trivial
examples of decorator use, addresses anything in the general case.


It doesn't, yet. Again, this is only targeting method types at the moment.
As far as a "better, less objectionable solution" - as I've said time and time
again, this subject has had 2+ years of discussion. Do you honestly
expect that 2 or 3 more weeks here or there is going to produce some
blinding flash of insight? I'd love it to be true, but really, I can't see it.


We're about to do something to the language that will make it less
readable and more intimidating. That's bad. So maybe if we limit the
scope of what decorators need to do, they won't be used that often. And
that would be good.

Jul 18 '05 #5

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

Similar topics

0
1612
by: Robin Becker | last post by:
A colleague wanted to initialize his class __new__ and tried code resembling this #######################1 class Metaclass (type): def __init__(cls, name, bases, *args, **kwargs): super(Metaclass, cls).__init__(cls, name, bases, *args, **kwargs) print 'cls=',cls, cls.__new cls.__new__ = staticmethod(cls.__new) def __new(self,cls,*args):
5
2261
by: Irmen de Jong | last post by:
Hi, I've developed the Metaclass below, because I needed a way to make a bunch of classes thread-safe. I didn't want to change every method of the class by adding lock.aqcuire()..lock.release() around the existing code. So I made a metaclass that essentially replaces every method of a class with a 'wrapper' method, that does the locking, invocation, unlocking. Is this the right approach? It seems to work fine. But I have
33
2520
by: Jacek Generowicz | last post by:
I would like to write a metaclass which would allow me to overload names in the definition of its instances, like this class Foo(object): __metaclass__ = OverloadingClass att = 1 att = 3
2
1941
by: zipher | last post by:
After searching through comp.lang.python and the web regarding metaclasses, I could not find an example for customing classes using metaclass parameters. I want to be able to create a class at runtime by calling some function or 'meta-constructor' which returns a customized class and sets a class attribute according a given parameter. Ideally, I'd be able to do something like:
16
1616
by: ironfroggy | last post by:
Hoping this isn't seeming too confusing, but I need to create a metaclass and a class using that metaclass, such that one of the bases of the metaclass is the class created with that metaclass. I can't figure out a way to do this, even after trying to add the class as a base after the classes have been created. Is there some way I can get this to work properly?
14
2028
by: Pedro Werneck | last post by:
Hi I have a class A, with metaclass M_A, and class B, subclass of A, with metaclass M_B, subclass of M_A. A class C, subclass of B must have M_B or a subclass of it as metaclass, but what if I need to 'disable' the code in M_B on C ? The correct way to do that seems to be with a M_C metaclass, subclass of M_B, implementing but not calling parent class methods, or calling 'type' methods.
9
1659
by: Christian Eder | last post by:
Hi, I think I have discovered a problem in context of metaclasses and multiple inheritance in python 2.4, which I could finally reduce to a simple example: Look at following code: class M_A (type) :
4
3312
by: Pedro Werneck | last post by:
Hi all I noticed something strange here while explaining decorators to someone. Not any real use code, but I think it's worth mentioning. When I access a class attribute, on a class with a custom metaclass with a __getattribute__ method, the method is used when acessing some attribute directly with the class object, but not when you do it from the instance.
2
1965
by: lbolognini | last post by:
Hi all, I dare risk my brain exploding by reaching for the understanding of metaclasses. At first i thought i almost got them, even if vaguely back in a corner of my mind, my understanding was that, as classes' class a metaclass would be able to return a different class based on input... .... until i thought of factory functions and, Python considering
0
9001
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8860
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8832
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7672
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6498
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5841
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4348
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4587
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2281
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.